dynamodb-toolbox
Version:
Lightweight and type-safe query builder for DynamoDB and TypeScript.
32 lines (31 loc) • 1.44 kB
JavaScript
import { z } from 'zod';
export const withDefault = (schema, { fill }, zodSchema) => fill === false
? zodSchema
: schema.props.key === true && schema.props.keyDefault !== undefined
? zodSchema.default(schema.props.keyDefault)
: schema.props.putDefault !== undefined
? zodSchema.default(schema.props.putDefault)
: zodSchema;
export const withOptional = (schema, { defined }, zodSchema) => defined === true
? zodSchema
: schema.props.required === 'never'
? z.optional(zodSchema)
: zodSchema;
export const withEncoding = (schema, { transform }, zodSchema) => transform === false
? zodSchema
: schema.props.transform !== undefined
? zodSchema.transform(decoded => schema.props.transform.encode(decoded))
: zodSchema;
export const withAttributeNameEncoding = (schema, { transform }, zodSchema) => transform === false ||
Object.values(schema.attributes).every(attribute => attribute.props.savedAs === undefined)
? zodSchema
: zodSchema.transform(compileAttributeNameEncoder(schema));
export const compileAttributeNameEncoder = (schema) => (decoded) => {
var _a;
const encoded = {};
for (const [attrName, attribute] of Object.entries(schema.attributes)) {
const savedAs = (_a = attribute.props.savedAs) !== null && _a !== void 0 ? _a : attrName;
encoded[savedAs] = decoded[attrName];
}
return encoded;
};