dynamodb-toolbox
Version:
Lightweight and type-safe query builder for DynamoDB and TypeScript.
32 lines (31 loc) • 1.53 kB
JavaScript
import { z } from 'zod';
import { withValidate } from '../utils.js';
import { schemaZodParser } from './schema.js';
import { withDefault, withOptional } from './utils.js';
const withEncodedKeys = (schema, { transform }, zodSchema) => transform === false
? zodSchema
: schema.keys.props.transform !== undefined
? zodSchema.transform(compileKeysEncoder(schema))
: zodSchema;
export const compileKeysEncoder = (schema) => (decoded) => {
const encoded = {};
for (const [key, value] of Object.entries(decoded)) {
const encodedKey = schema.keys.props.transform.encode(key);
encoded[encodedKey] = value;
}
return encoded;
};
export const recordZodParser = (schema, options = {}) => {
let zodFormatter;
if (schema.keys.props.enum !== undefined && schema.props.partial !== true) {
const elementsFormatter = schemaZodParser(schema.elements, { ...options, defined: false });
/**
* @debt dependency "Using ZodObject until ZodStrictRecord is a thing: https://github.com/colinhacks/zod/issues/2623"
*/
zodFormatter = withEncodedKeys(schema, options, z.object(Object.fromEntries(schema.keys.props.enum.map(key => [key, elementsFormatter]))));
}
else {
zodFormatter = z.record(schemaZodParser(schema.keys, { ...options, defined: true }), schemaZodParser(schema.elements, { ...options, defined: true }));
}
return withDefault(schema, options, withOptional(schema, options, withValidate(schema, zodFormatter)));
};