make generic handler

This commit is contained in:
Nate Kelley 2025-07-16 09:59:30 -06:00
parent 0d01dfcb4c
commit a032a966f8
No known key found for this signature in database
GPG Key ID: FD90372AB8D98B4F
1 changed files with 24 additions and 36 deletions

View File

@ -1,5 +1,27 @@
import { z } from 'zod'; import { z } from 'zod';
/**
* The core preprocessing logic for converting query parameters into arrays
*/
const queryArrayPreprocessFn = (val: unknown) => {
// Handle no value
if (!val) return undefined;
// Already an array, pass through
if (Array.isArray(val)) return val;
// Handle string input (single or comma-separated)
if (typeof val === 'string') {
return val
.split(',')
.map((item) => item.trim())
.filter(Boolean);
}
// Single value case (wrap in array)
return [val];
};
/** /**
* Creates a preprocessor that converts query parameter strings into arrays. * Creates a preprocessor that converts query parameter strings into arrays.
* Handles various input formats: * Handles various input formats:
@ -9,46 +31,12 @@ import { z } from 'zod';
* - No value: undefined undefined * - No value: undefined undefined
*/ */
export const createQueryArrayPreprocessor = <T>(schema: z.ZodArray<z.ZodType<T>>) => { export const createQueryArrayPreprocessor = <T>(schema: z.ZodArray<z.ZodType<T>>) => {
return z.preprocess((val) => { return z.preprocess(queryArrayPreprocessFn, schema);
// Handle no value
if (!val) return undefined;
// Already an array, pass through
if (Array.isArray(val)) return val;
// Handle string input (single or comma-separated)
if (typeof val === 'string') {
return val
.split(',')
.map((item) => item.trim())
.filter(Boolean);
}
// Single value case (wrap in array)
return [val];
}, schema);
}; };
/** /**
* Type-safe helper for creating optional query array preprocessors * Type-safe helper for creating optional query array preprocessors
*/ */
export const createOptionalQueryArrayPreprocessor = <T>(itemSchema: z.ZodType<T>) => { export const createOptionalQueryArrayPreprocessor = <T>(itemSchema: z.ZodType<T>) => {
return z.preprocess((val) => { return z.preprocess(queryArrayPreprocessFn, z.array(itemSchema).optional());
// Handle no value
if (!val) return undefined;
// Already an array, pass through
if (Array.isArray(val)) return val;
// Handle string input (single or comma-separated)
if (typeof val === 'string') {
return val
.split(',')
.map((item) => item.trim())
.filter(Boolean);
}
// Single value case (wrap in array)
return [val];
}, z.array(itemSchema).optional());
}; };