@zod-plugins/utils
Version:
export some functions to help you use zod
82 lines • 2.75 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.preParseFromRecordString = void 0;
const zod_1 = require("zod");
function preParseSingle(schema, value) {
if (typeof value !== 'string')
return value; // 可能为undefined
if (schema instanceof zod_1.z.ZodNumber) {
return /^[-]?\d+$/.test(value) ? Number(value) : value;
}
if (schema instanceof zod_1.z.ZodObject ||
schema instanceof zod_1.z.ZodArray ||
schema instanceof zod_1.z.ZodRecord ||
schema instanceof zod_1.z.ZodTuple) {
try {
const parsedData = JSON.parse(value);
return parsedData;
}
catch {
return value;
}
}
if (schema instanceof zod_1.z.ZodLazy) {
return preParseSingle(schema._def.getter(), value);
}
if (schema instanceof zod_1.z.ZodNativeEnum) {
const values = Object.values(schema.enum);
for (const val of values) {
if (val === value || val === Number(value)) {
return val;
}
}
}
if (schema instanceof zod_1.z.ZodOptional) {
return preParseSingle(schema.unwrap(), value);
}
if (schema instanceof zod_1.z.ZodBoolean) {
return value === 'true' ? true : value === 'false' ? false : value;
}
return value;
}
function preParseToRecordOrObject(schema) {
if (schema instanceof zod_1.z.ZodRecord) {
return zod_1.z.record(schema.keySchema, zod_1.z.preprocess(val => preParseSingle(schema.valueSchema, val), schema.valueSchema));
}
else if (schema instanceof zod_1.z.ZodObject) {
const newShape = {};
for (const key in schema.shape) {
const fieldSchema = schema.shape[key];
newShape[key] = zod_1.z.preprocess(val => preParseSingle(fieldSchema, val), fieldSchema);
}
return new zod_1.z.ZodObject({
...schema._def,
shape: () => newShape,
});
}
return undefined;
}
/**
* 将schema第一层的value做preprocess处理
* 应用场景是一体化中为get请求做parse
*
* @example
* ```typescript
* const schema = preParseFromRecordString(z.object({
* a: z.number()
* }));
* ---> 转换后:
* const schema = z.object({
* a: z.preprocess(val => Number(val), z.number())
* });
* ```
```
*/
function preParseFromRecordString(schema) {
const result = preParseToRecordOrObject(schema instanceof zod_1.z.ZodLazy ? schema.schema : schema);
if (result)
return result;
throw new Error('only support schema type: ZodObject、ZodLazy(() => ZodObject)');
}
exports.preParseFromRecordString = preParseFromRecordString;
//# sourceMappingURL=utils.js.map
;