@flotiq/flotiq-astro-sdk
Version:
Astro collection generator for connecting with Flotiq CMS
70 lines (69 loc) • 2.93 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTypeForProperty = getTypeForProperty;
function getTypeForProperty(schema, propertyConfig, required, propertyName) {
var _a;
const type = schema === null || schema === void 0 ? void 0 : schema.type;
const format = schema === null || schema === void 0 ? void 0 : schema.format;
const ref = schema === null || schema === void 0 ? void 0 : schema.$ref;
const enumValues = schema === null || schema === void 0 ? void 0 : schema.enum;
const items = schema === null || schema === void 0 ? void 0 : schema.items;
const optional = !required.includes(propertyName) ? '.optional()' : '';
if (ref) {
if ((_a = propertyConfig.validation) === null || _a === void 0 ? void 0 : _a.relationContenttype) {
return `reference('${propertyConfig.validation.relationContenttype}')${optional}`;
}
return ref.split('/').pop(); // Assuming definitions are in the same scope
}
else if (enumValues) {
return `z.enum([${enumValues.map((v) => `'${v}'`).join(', ')}])${optional}`;
}
else if (type === 'string') {
if (format === 'date-time') {
return `z.coerce.date()${optional}`;
}
else if (format === 'date') {
return `z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/)${optional}`; // Basic date regex
}
else {
return `z.string()${optional}`;
}
}
else if (type === 'number') {
return `z.number()${optional}`;
}
else if (type === 'integer') {
return `z.number().int()${optional}`;
}
else if (type === 'boolean') {
return `z.boolean()${optional}`;
}
else if (type === 'array') {
if (items) {
return `z.array(${getTypeForProperty(items, propertyConfig, schema.required || [], '')})${optional}`;
}
else {
return 'z.array(z.any())';
}
}
else if (type === 'object') {
const properties = (schema === null || schema === void 0 ? void 0 : schema.properties) || {};
const requiredNested = (schema === null || schema === void 0 ? void 0 : schema.required) || [];
const nestedZodProperties = {};
for (const propName in properties) {
if (properties.hasOwnProperty(propName)) {
nestedZodProperties[propName] = schema.properties[propName];
}
}
const nestedZodObjectEntries = Object.entries(nestedZodProperties)
.map(([name]) => {
var _a;
return ` ${name}: ${getTypeForProperty(schema.properties[name], (_a = propertyConfig.items) === null || _a === void 0 ? void 0 : _a.propertiesConfig[name], requiredNested, name)},`;
})
.join('');
return `z.object({${nestedZodObjectEntries}})${optional}\n`;
}
else {
return 'z.any()';
}
}