UNPKG

dynamodb-toolbox

Version:

Lightweight and type-safe query builder for DynamoDB and TypeScript.

37 lines (36 loc) 1.84 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.recordZodFormatter = exports.compileKeysDecoder = void 0; const zod_1 = require("zod"); const utils_js_1 = require("../utils.js"); const schema_js_1 = require("./schema.js"); const utils_js_2 = require("./utils.js"); const withDecodedKeys = (schema, { transform }, zodSchema) => transform === false ? zodSchema : schema.keys.props.transform !== undefined ? zod_1.z.preprocess((0, exports.compileKeysDecoder)(schema), zodSchema) : zodSchema; const compileKeysDecoder = (schema) => (encoded) => { const decoded = {}; for (const [key, value] of Object.entries(encoded)) { const decodedKey = schema.keys.props.transform.decode(key); decoded[decodedKey] = value; } return decoded; }; exports.compileKeysDecoder = compileKeysDecoder; const recordZodFormatter = (schema, options = {}) => { let zodFormatter; if (schema.keys.props.enum !== undefined && schema.props.partial !== true) { const elementsFormatter = (0, schema_js_1.schemaZodFormatter)(schema.elements, { ...options, defined: false }); /** * @debt dependency "Using ZodObject until ZodStrictRecord is a thing: https://github.com/colinhacks/zod/issues/2623" */ zodFormatter = withDecodedKeys(schema, options, zod_1.z.object(Object.fromEntries(schema.keys.props.enum.map(key => [key, elementsFormatter])))); } else { zodFormatter = zod_1.z.record((0, schema_js_1.schemaZodFormatter)(schema.keys, { ...options, defined: true }), (0, schema_js_1.schemaZodFormatter)(schema.elements, { ...options, defined: true })); } return (0, utils_js_2.withOptional)(schema, options, (0, utils_js_1.withValidate)(schema, zodFormatter)); }; exports.recordZodFormatter = recordZodFormatter;