Enhancement: Better content type creation for Astro #704

This commit is contained in:
Elio Struyf
2023-11-11 10:38:31 -08:00
parent 11354ad8e5
commit e1f6c90fc0
+48 -2
View File
@@ -3,7 +3,8 @@ import { join } from 'path';
import { createServer } from 'vite';
import zod from 'astro/zod';
const { ZodDefault, ZodObject, ZodOptional, ZodString, ZodEffects, ZodEnum } = zod;
const { ZodDefault, ZodObject, ZodOptional, ZodString, ZodEffects, ZodEnum, ZodUnion, ZodArray } =
zod;
/**
* Process the Zod field
@@ -21,6 +22,17 @@ function getField(field, isOptional = false, defaultValue = undefined) {
return getField(type, isOptional, defaultValue);
}
if (field instanceof ZodEffects) {
const type = field.sourceType();
return getField(type, isOptional, defaultValue);
}
if (field instanceof ZodUnion) {
const types = field._def.options;
const type = types[0];
return getField(type, isOptional, defaultValue);
}
if (field instanceof ZodDefault) {
// https://github.com/colinhacks/zod/blob/master/README.md#default
isOptional = true;
@@ -61,6 +73,26 @@ function generateFieldInfo(name, type) {
required: !isFieldOptional
};
switch (fieldInfo.type) {
case 'ZodString':
fieldInfo.type = 'string';
break;
case 'ZodNumber':
fieldInfo.type = 'number';
break;
case 'ZodBoolean':
fieldInfo.type = 'boolean';
break;
case 'ZodDate':
fieldInfo.type = 'datetime';
break;
case 'ZodArray':
fieldInfo.type = 'choice';
break;
default:
break;
}
if (fieldType instanceof ZodObject) {
const subFields = extractFieldInfoFromShape(fieldType);
@@ -71,10 +103,24 @@ function generateFieldInfo(name, type) {
fieldInfo.type = fieldType.sourceType().fmFieldType;
}
if (fieldInfo.name.toLowerCase().includes('image')) {
fieldInfo.type = 'image';
}
if (fieldType instanceof ZodEnum) {
fieldInfo.options = fieldType.options;
}
if (fieldType instanceof ZodArray) {
if (fieldInfo.name === 'tags') {
fieldInfo.type = 'tags';
} else if (fieldInfo.name === 'categories') {
fieldInfo.type = 'categories';
} else {
fieldInfo.options = fieldType.options;
}
}
if (fieldType instanceof ZodString) {
// https://github.com/StefanTerdell/zod-to-json-schema/blob/master/src/parsers/string.ts#L45
if (fieldType._def.checks && fieldType._def.checks.length > 0) {
@@ -205,7 +251,7 @@ const astroContentModulePlugin = () => {
writeFileSync(
join(process.cwd(), `./.frontmatter/temp/astro.collections.json`),
JSON.stringify(processedCollections)
JSON.stringify(processedCollections, null, 2)
);
console.log('Collections generated successfully');