dynamodb-toolbox
Version:
Lightweight and type-safe query builder for DynamoDB and TypeScript.
25 lines (24 loc) • 1.13 kB
JavaScript
import { z } from 'zod';
export const withOptional = (schema, { partial, defined }, zodSchema) => defined === true
? zodSchema
: partial === true || schema.props.required === 'never'
? z.optional(zodSchema)
: zodSchema;
export const withDecoding = (schema, { transform }, zodSchema) => transform === false
? zodSchema
: schema.props.transform !== undefined
? z.preprocess(encoded => schema.props.transform.decode(encoded), zodSchema)
: zodSchema;
export const withAttributeNameDecoding = (schema, { transform }, zodSchema) => transform === false ||
Object.values(schema.attributes).every(attribute => attribute.props.savedAs === undefined)
? zodSchema
: z.preprocess(compileAttributeNameDecoder(schema), zodSchema);
export const compileAttributeNameDecoder = (schema) => (encoded) => {
var _a;
const decoded = {};
for (const [attrName, attribute] of Object.entries(schema.attributes)) {
const savedAs = (_a = attribute.props.savedAs) !== null && _a !== void 0 ? _a : attrName;
decoded[attrName] = encoded[savedAs];
}
return decoded;
};