UNPKG

@backland/schema

Version:

TypeScript schema declaration and validation library with static type inference

76 lines (75 loc) 2.25 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.LiteralField = void 0; var _utils = require("@backland/utils"); var _FieldType = require("./FieldType"); const PROTO_KEY = '__o.proto__'; class LiteralField extends _FieldType.FieldType { __isLiteralField = true; static utils = { deserialize(def) { const isFinalDef = def && typeof def === 'object' && PROTO_KEY in def; if (!isFinalDef) { throw new Error(`Invalid LiteralFieldDef: ` + (0, _utils.inspectObject)(def)); } const typename = (0, _utils.getTypeName)(def.value); if (def[PROTO_KEY] === typename) return def.value; try { return _utils.BJSON.parse(def.value); } catch (e) { throw new _utils.RuntimeError(`Failed deserialize value`, { ...def }); } }, serialize(value) { if (typeof value === 'string') return value; try { return _utils.BJSON.stringify(value); } catch (e) { throw new _utils.RuntimeError(`Failed to serialize`, { // }); } }, toDef(input) { if (LiteralField.isLiteralFieldDef(input)) return input; return { [PROTO_KEY]: (0, _utils.getTypeName)(input), value: LiteralField.utils.serialize(input) }; } }; constructor(def) { super({ def: LiteralField.utils.toDef(def), name: 'literal' }); const expected = this.def.value; this.parse = this.applyParser({ parse(input) { const received = LiteralField.utils.serialize(input); if (expected !== received) { throw new Error(`Unexpected literal value:\nExpected:\n${expected}\nReceived:\n${received}`); } return input; } }); } static create = def => { return new LiteralField(def); }; static isFinalTypeDef(t) { return (t === null || t === void 0 ? void 0 : t.type) === 'literal'; } static is(t) { return (t === null || t === void 0 ? void 0 : t.__isLiteralField) === true; } static isLiteralFieldDef(t) { return typeof (t === null || t === void 0 ? void 0 : t[PROTO_KEY]) === 'string'; } } exports.LiteralField = LiteralField; //# sourceMappingURL=LiteralField.js.map