nosql-constraints
Version:
Helpers to manage constrants (i.e. cascade delete) in a NoSQL database
62 lines • 2.01 kB
JavaScript
import { ZodArray, ZodDiscriminatedUnion, ZodLiteral, ZodNumber, ZodObject, ZodString, ZodUnion } from 'zod';
export function zod(schema) {
return new ZodAdapter(schema);
}
class ZodAdapter {
#schema;
constructor(schema) {
this.#schema = schema;
}
extractChunks() {
return extractChunks(this.#schema, undefined);
}
}
function extractChunks(schema, parentPath) {
if (schema instanceof ZodUnion) {
return schema.options.map((option) => extractChunks(option, parentPath)).flat();
}
else if (schema instanceof ZodDiscriminatedUnion) {
return schema.options.map((option) => extractChunks(option, parentPath)).flat();
}
else if (schema instanceof ZodObject) {
return [extractChunkFromObject(schema, parentPath)];
}
else if (schema instanceof ZodString) {
return [{ path: parentPath, type: 'string' }];
}
else if (schema instanceof ZodNumber) {
return [{ path: parentPath, type: 'number' }];
}
else if (schema instanceof ZodLiteral) {
return [{ path: parentPath, type: 'literal', value: schema.value }];
}
else if (schema instanceof ZodArray) {
return [extractChunksFromArray(schema, parentPath)];
}
else {
throw new Error(`Unsupported schema type: ${schema.constructor.name}`);
}
}
function extractChunkFromObject(schema, parentPath) {
const properties = {};
for (const [key, value] of Object.entries(schema.shape)) {
const path = `${parentPath ? `${parentPath}.` : ''}${key}`;
properties[key] = extractChunks(value, path);
}
return {
path: parentPath,
type: 'object',
properties
};
}
function extractChunksFromArray(schema, parentPath) {
const path = parentPath ? `${parentPath}.[]` : '[]';
return {
path: parentPath,
type: 'array',
properties: {
'[]': extractChunks(schema.element, path)
}
};
}
//# sourceMappingURL=zod.js.map