UNPKG

skema

Version:

Skema provides a handy & composable way to validate / transform / purify the input data.

87 lines (71 loc) 1.81 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Context = void 0; var _error = require("./error"); var _util = require("./util"); var _future = require("./future"); const CUSTOM_ERROR = 'CUSTOM_ERROR'; // data = {a: {b: 1}} // 1. value: data, key: null, parent: null, path: [] // 2. descend 'a': value: {b: 1}, key: 'a', parent: data, path: ['a'] // 3. descend 'b': value: 1, key: 'b', parent: {b: 1}, path: ['a', 'b'] class Context { constructor(input, key = null, parent = null, path = []) { this.input = input; this.rawKey = key; this.key = key; this.rawParent = parent; this.parent = null; this.path = path; } get context() { const { rawKey, key, rawParent, parent, path, input } = this; return { rawKey, key, rawParent, parent, path, input }; } descend(key) { return new Context(this.input[key], key, this.input, this.path.concat(key)); } _wrap(error) { // rawParent and parent will be removed by context later assign(error, 'key', this.key); assign(error, 'rawKey', this.rawKey); assign(error, 'input', this.input); assign(error, 'path', this.path); (0, _util.defineValue)(error, _future.TYPE_ERROR, true); return error; } makeError(error) { if ((0, _future.isError)(error)) { return error; } const err = error instanceof Error ? error : new Error(error); assign(err, 'code', CUSTOM_ERROR); return this._wrap(err); } errorByCode(code, ...args) { const err = (0, _error.error)(code, ...args); return this._wrap(err); } } exports.Context = Context; function assign(object, key, value) { if (key in object) { return; } object[key] = value; }