1 import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types"
2 import type {KeywordCxt} from "../../compile/validate"
3 import {_, not, getProperty, Name} from "../../compile/codegen"
4 import {checkMetadata} from "./metadata"
5 import {checkNullableObject} from "./nullable"
6 import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error"
7 import {DiscrError, DiscrErrorObj} from "../discriminator/types"
9 export type JTDDiscriminatorError =
10 | _JTDTypeError<"discriminator", "object", string>
11 | DiscrErrorObj<DiscrError.Tag>
12 | DiscrErrorObj<DiscrError.Mapping>
14 const error: KeywordErrorDefinition = {
16 const {schema, params} = cxt
17 return params.discrError
18 ? params.discrError === DiscrError.Tag
19 ? `tag "${schema}" must be string`
20 : `value of tag "${schema}" must be in mapping`
21 : typeErrorMessage(cxt, "object")
24 const {schema, params} = cxt
25 return params.discrError
26 ? _`{error: ${params.discrError}, tag: ${schema}, tagValue: ${params.tag}}`
27 : typeErrorParams(cxt, "object")
31 const def: CodeKeywordDefinition = {
32 keyword: "discriminator",
34 implements: ["mapping"],
36 code(cxt: KeywordCxt) {
38 const {gen, data, schema, parentSchema} = cxt
39 const [valid, cond] = checkNullableObject(cxt, data)
42 validateDiscriminator()
43 gen.elseIf(not(valid))
48 function validateDiscriminator(): void {
49 const tag = gen.const("tag", _`${data}${getProperty(schema)}`)
50 gen.if(_`${tag} === undefined`)
51 cxt.error(false, {discrError: DiscrError.Tag, tag})
52 gen.elseIf(_`typeof ${tag} == "string"`)
55 cxt.error(false, {discrError: DiscrError.Tag, tag}, {instancePath: schema})
59 function validateMapping(tag: Name): void {
61 for (const tagValue in parentSchema.mapping) {
62 gen.elseIf(_`${tag} === ${tagValue}`)
63 gen.assign(valid, applyTagSchema(tagValue))
68 {discrError: DiscrError.Mapping, tag},
69 {instancePath: schema, schemaPath: "mapping", parentSchema: true}
74 function applyTagSchema(schemaProp: string): Name {
75 const _valid = gen.name("valid")
80 jtdDiscriminator: schema,