dynamodb-toolbox
Version:
Lightweight and type-safe query builder for DynamoDB and TypeScript.
32 lines (31 loc) • 1.5 kB
JavaScript
import { z } from 'zod';
import { withValidate } from '../utils.js';
import { schemaZodFormatter } from './schema.js';
import { withOptional } from './utils.js';
const withDecodedKeys = (schema, { transform }, zodSchema) => transform === false
? zodSchema
: schema.keys.props.transform !== undefined
? z.preprocess(compileKeysDecoder(schema), zodSchema)
: zodSchema;
export 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;
};
export const recordZodFormatter = (schema, options = {}) => {
let zodFormatter;
if (schema.keys.props.enum !== undefined && schema.props.partial !== true) {
const elementsFormatter = 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, z.object(Object.fromEntries(schema.keys.props.enum.map(key => [key, elementsFormatter]))));
}
else {
zodFormatter = z.record(schemaZodFormatter(schema.keys, { ...options, defined: true }), schemaZodFormatter(schema.elements, { ...options, defined: true }));
}
return withOptional(schema, options, withValidate(schema, zodFormatter));
};