| 1 | import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" |
| 2 | import type {KeywordCxt} from "../../compile/validate" |
| 3 | import {_, str, operators, Code} from "../../compile/codegen" |
| 4 | |
| 5 | const ops = operators |
| 6 | |
| 7 | type Kwd = "maximum" | "minimum" | "exclusiveMaximum" | "exclusiveMinimum" |
| 8 | |
| 9 | type Comparison = "<=" | ">=" | "<" | ">" |
| 10 | |
| 11 | const KWDs: {[K in Kwd]: {okStr: Comparison; ok: Code; fail: Code}} = { |
| 12 | maximum: {okStr: "<=", ok: ops.LTE, fail: ops.GT}, |
| 13 | minimum: {okStr: ">=", ok: ops.GTE, fail: ops.LT}, |
| 14 | exclusiveMaximum: {okStr: "<", ok: ops.LT, fail: ops.GTE}, |
| 15 | exclusiveMinimum: {okStr: ">", ok: ops.GT, fail: ops.LTE}, |
| 16 | } |
| 17 | |
| 18 | export type LimitNumberError = ErrorObject< |
| 19 | Kwd, |
| 20 | {limit: number; comparison: Comparison}, |
| 21 | number | {$data: string} |
| 22 | > |
| 23 | |
| 24 | const error: KeywordErrorDefinition = { |
| 25 | message: ({keyword, schemaCode}) => str`must be ${KWDs[keyword as Kwd].okStr} ${schemaCode}`, |
| 26 | params: ({keyword, schemaCode}) => |
| 27 | _`{comparison: ${KWDs[keyword as Kwd].okStr}, limit: ${schemaCode}}`, |
| 28 | } |
| 29 | |
| 30 | const def: CodeKeywordDefinition = { |
| 31 | keyword: Object.keys(KWDs), |
| 32 | type: "number", |
| 33 | schemaType: "number", |
| 34 | $data: true, |
| 35 | error, |
| 36 | code(cxt: KeywordCxt) { |
| 37 | const {keyword, data, schemaCode} = cxt |
| 38 | cxt.fail$data(_`${data} ${KWDs[keyword as Kwd].fail} ${schemaCode} || isNaN(${data})`) |
| 39 | }, |
| 40 | } |
| 41 | |
| 42 | export default def |