UNPKG

normul

Version:

Normul is a tiny TypeScript/JavaScript library for data normalization and transformation

83 lines 2.28 kB
import { isObject } from '../../utils.js'; import { Schema } from '../Schema.js'; export class ObjectSchema extends Schema { shape; mode = 'strip'; constructor(shape) { super(); this.shape = shape; } _normalize(input, ctx) { if (!isObject(input)) { this.makeIssue({ ctx, message: 'Converted to object', level: 'warn', expected: 'object', received: input, }); } const object = { ...input }; const result = {}; for (const key in this.shape) { ctx.path.push(key); result[key] = this.invokeNormalize(this.shape[key], object[key], ctx); ctx.path.pop(); } if (this.mode === 'passthrough') { for (const key in object) { if (!(key in this.shape)) { result[key] = object[key]; } } } return result; } get strip() { const result = this.clone(); result.mode = 'strip'; return result; } get passthrough() { const result = this.clone(); result.mode = 'passthrough'; return result; } extend(schemaOrShape) { const result = this.clone(); result.shape = { ...result.shape, ...(schemaOrShape instanceof ObjectSchema ? schemaOrShape.shape : schemaOrShape), }; return result; } pick(keys) { const pickedShape = {}; for (const key of keys) { if (key in this.shape) { pickedShape[key] = this.shape[key]; } } const result = this.clone(); result.shape = pickedShape; return result; } omit(keys) { const omittedShape = { ...this.shape }; for (const key of keys) { if (key in omittedShape) { delete omittedShape[key]; } } const result = this.clone(); result.shape = omittedShape; return result; } cloneArgs() { return [this.shape]; } cloneProps(target) { target.mode = this.mode; } } //# sourceMappingURL=ObjectSchema.js.map