Skip to content

Instantly share code, notes, and snippets.

@saiashirwad
Last active August 14, 2023 08:02
Show Gist options
  • Save saiashirwad/5f2211efd6282dbd4b41a8ae2c95b74b to your computer and use it in GitHub Desktop.
Save saiashirwad/5f2211efd6282dbd4b41a8ae2c95b74b to your computer and use it in GitHub Desktop.
w00t
const createFormSchema = (
items: FormItem[],
): z.ZodObject<Record<string, never>> => {
const entries = items.map((formItem) => {
let schema = match<FormItem, z.ZodType>(formItem)
.with({ type: "DATE" }, () => z.date())
.with({ type: "NUMBER", data: { type: "NUMBER" } }, (item) => {
let schema = z.number();
if (item.data.min) {
schema = schema.min(item.data.min);
}
if (item.data.max) {
schema = schema.max(item.data.max);
}
return schema;
})
.with({ type: P.union("LONG_TEXT", "TEXT") }, () => z.string())
.with({ type: "FIELD" }, () => z.any())
.with({ type: "MULTI_SELECT" }, (item) => {
let schema = z.array(z.string());
if (item.required) {
schema = schema.min(1);
}
return schema;
})
.with({ type: "SINGLE_SELECT" }, () => z.string())
.otherwise(() => z.string());
schema = !formItem.required ? schema.nullable() : schema;
return [formItem.id, schema] as const;
});
return z.object(Object.fromEntries(entries) as never);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment