Add JSON field parser with flexible type transformation

This commit is contained in:
2025-10-10 08:52:43 +02:00
parent 21c9fccf5e
commit d4dfed9603
2 changed files with 50 additions and 7 deletions

View File

@@ -33,6 +33,41 @@ export const RecordModel = z.object({
});
export type RecordModel = z.infer<typeof RecordModel>;
/******* JSON FIELD *******/
export const pbJsonField = (maxSizeInBytes: number = 1048576) => {
const literalSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
const jsonSchema: z.ZodType<any> = z.lazy(() =>
z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)])
);
const stringTransform = z.string()
.max(maxSizeInBytes, `JSON field cannot exceed ${maxSizeInBytes} bytes`)
.transform((val) => {
if (val === "true") return true;
if (val === "false") return false;
if (val === "null") return null;
if ((val.startsWith('[') && val.endsWith(']'))||(val.startsWith('{') && val.endsWith('}')))
try {
return JSON.parse(val);
} catch {
return val;
}
const num = Number(val);
if (!isNaN(num) && isFinite(num) && val.trim() !== '')
return num;
if (val.startsWith('"') && val.endsWith('"'))
return val.slice(1, -1);
return val;
});
return z.union([jsonSchema, stringTransform]);
};
/******* RECORDS *******/
@@_RECORDS_@@