Improves boolean parsing for 'purchased' field

Updates the StoreItemSchema to handle various input formats for the 'purchased' field, including strings and numbers.

This ensures that the application can correctly interpret boolean values from different sources, preventing data validation errors and improving the user experience.

Adds a preprocess function to the schema to convert string values like "on", "true", "1", "off", "false", and "0", and number values of 1 and 0 to their respective boolean equivalents before validation.
This commit is contained in:
Chenwei Jiang 2025-08-21 15:46:00 +08:00
parent 4480be656a
commit 11104dbf29
Signed by: cheverjohn
GPG key ID: ADC4815BFE960182

View file

@ -44,7 +44,15 @@ const StoreItemSchema = z.object({
category: z.string(), category: z.string(),
site: z.string(), site: z.string(),
batch: z.string(), batch: z.string(),
purchased: z.boolean(), purchased: z.preprocess((v) => {
if (typeof v === 'string') {
const s = v.toLowerCase();
if (s === 'on' || s === 'true' || s === '1') return true;
if (s === 'off' || s === 'false' || s === '0') return false;
}
if (typeof v === 'number') return v === 1 ? true : v === 0 ? false : v;
return v;
}, z.boolean()),
weight: z.number(), weight: z.number(),
purchaseLink: z.string().optional() purchaseLink: z.string().optional()
}); });