Add JSON field parser with flexible type transformation
This commit is contained in:
@@ -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_@@
|
||||
|
||||
|
||||
Reference in New Issue
Block a user