2023-04-10 10:02:50 -07:00
|
|
|
import z from 'zod';
|
|
|
|
|
2022-04-16 10:57:17 -07:00
|
|
|
/** Use new value only if old value is undefined */
|
2022-03-24 12:27:27 -07:00
|
|
|
export const mergeDefined = (oldVal: any, newVal: any) => oldVal === undefined ? newVal : oldVal;
|
|
|
|
|
|
|
|
export const makeEmojiMap = (emojis: any) => emojis.reduce((obj: any, emoji: any) => {
|
|
|
|
obj[`:${emoji.shortcode}:`] = emoji;
|
|
|
|
return obj;
|
|
|
|
}, {});
|
|
|
|
|
|
|
|
/** Normalize entity ID */
|
|
|
|
export const normalizeId = (id: any): string | null => {
|
|
|
|
return typeof id === 'string' ? id : null;
|
|
|
|
};
|
2023-04-10 10:02:50 -07:00
|
|
|
|
|
|
|
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);
|
|
|
|
};
|