UNPKG

@jsonjoy.com/json-type

Version:

High-performance JSON Pointer implementation

180 lines (179 loc) 4.12 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SchemaBuilder = void 0; class SchemaBuilder { get str() { return this.String(); } get num() { return this.Number(); } get bool() { return this.Boolean(); } get undef() { return this.Const(undefined); } get nil() { return this.Const(null); } get arr() { return this.Array(this.any); } get obj() { return this.Object(); } get map() { return this.Map(this.any); } get bin() { return this.Binary(this.any); } get any() { return this.Any(); } get fn() { return this.Function(this.any, this.any); } get fn$() { return this.Function$(this.any, this.any); } Boolean(a, b) { if (typeof a === 'string') return this.Boolean({ id: a, ...(b || {}) }); return { kind: 'bool', ...(a || {}) }; } Number(options) { return { kind: 'num', ...options }; } String(a, b) { if (typeof a === 'string') return this.String({ id: a, ...(b || {}) }); return { kind: 'str', ...(a || {}) }; } // public Binary<T extends Schema>(options: Optional<BinarySchema<T>> & Pick<BinarySchema<T>, 'type'>): BinarySchema<T>; Binary(type, options = {}) { return { kind: 'bin', type, ...options, }; } Array(a, b, c) { if (typeof a === 'string') return this.Array(b, { id: a, ...(c || {}) }); return { kind: 'arr', ...b, type: a, }; } /** * Use TypeScript const when defining a constant value. * * * @example * * ```ts * s.Const('foo' as const); * ``` */ Const(value, options) { return { kind: 'con', value: value, ...options }; } Tuple(...types) { return { kind: 'tup', types }; } fields(...fields) { return fields; } Object(...args) { const first = args[0]; if (args.length === 1 && first && typeof first === 'object' && first.fields instanceof Array) return { kind: 'obj', ...first }; if (args.length >= 1 && args[0] instanceof Array) return this.Object({ fields: args[0], ...args[1], }); return this.Object({ fields: args }); } /** @deprecated Use `.prop`. */ Field(key, value, options = {}) { return { kind: 'field', key, value, ...options, }; } /** @deprecated Use `.propOpt`. */ FieldOpt(key, value, options = {}) { return { kind: 'field', key, value, ...options, optional: true, }; } /** Declares an object property. */ prop(key, value, options = {}) { return { kind: 'field', key, value, ...options, }; } /** Declares an optional object property. */ propOpt(key, value, options = {}) { return { kind: 'field', key, value, ...options, optional: true, }; } Map(value, key, options) { return { kind: 'map', value, ...(key && { key }), ...options }; } Any(options = {}) { return { kind: 'any', ...options, }; } Ref(ref) { return { kind: 'ref', ref: ref, }; } Or(...types) { return { kind: 'or', types, discriminator: ['num', -1], }; } Function(req, res) { return { kind: 'fn', req, res, }; } Function$(req, res) { return { kind: 'fn$', req, res, }; } } exports.SchemaBuilder = SchemaBuilder;