Add `toSchema` function, to convert any legacy normalizer into a zod schema
This commit is contained in:
parent
2315dbdae5
commit
901ff57e13
|
@ -1,3 +1,5 @@
|
||||||
|
import z from 'zod';
|
||||||
|
|
||||||
/** Use new value only if old value is undefined */
|
/** Use new value only if old value is undefined */
|
||||||
export const mergeDefined = (oldVal: any, newVal: any) => oldVal === undefined ? newVal : oldVal;
|
export const mergeDefined = (oldVal: any, newVal: any) => oldVal === undefined ? newVal : oldVal;
|
||||||
|
|
||||||
|
@ -10,3 +12,18 @@ export const makeEmojiMap = (emojis: any) => emojis.reduce((obj: any, emoji: any
|
||||||
export const normalizeId = (id: any): string | null => {
|
export const normalizeId = (id: any): string | null => {
|
||||||
return typeof id === 'string' ? id : null;
|
return typeof id === 'string' ? id : null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type Normalizer<V, R> = (value: V) => R;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Allows using any legacy normalizer function as a zod schema.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```ts
|
||||||
|
* const statusSchema = toSchema(normalizeStatus);
|
||||||
|
* statusSchema.parse(status);
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export const toSchema = <V, R>(normalizer: Normalizer<V, R>) => {
|
||||||
|
return z.custom<V>().transform<R>(normalizer);
|
||||||
|
};
|
Loading…
Reference in New Issue