error.ts 746 B

1234567891011121314151617181920212223
  1. import type {KeywordErrorDefinition, KeywordErrorCxt, ErrorObject} from "../../types"
  2. import {_, Code} from "../../compile/codegen"
  3. export type _JTDTypeError<K extends string, T extends string, S> = ErrorObject<
  4. K,
  5. {type: T; nullable: boolean},
  6. S
  7. >
  8. export function typeError(t: string): KeywordErrorDefinition {
  9. return {
  10. message: (cxt) => typeErrorMessage(cxt, t),
  11. params: (cxt) => typeErrorParams(cxt, t),
  12. }
  13. }
  14. export function typeErrorMessage({parentSchema}: KeywordErrorCxt, t: string): string {
  15. return parentSchema?.nullable ? `must be ${t} or null` : `must be ${t}`
  16. }
  17. export function typeErrorParams({parentSchema}: KeywordErrorCxt, t: string): Code {
  18. return _`{type: ${t}, nullable: ${!!parentSchema?.nullable}}`
  19. }