Skip to content

Instantly share code, notes, and snippets.

@RyanHirsch
Last active February 27, 2024 20:53
Show Gist options
  • Save RyanHirsch/c5b47b2bb5548a38afdc725f9a128925 to your computer and use it in GitHub Desktop.
Save RyanHirsch/c5b47b2bb5548a38afdc725f9a128925 to your computer and use it in GitHub Desktop.
Validator for taking camelcase or snake case inputs and converting them to a consistent type checked value.
import * as z from "zod";
const camelToSnakeCase = (str: string) =>
str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
const validActions = ["HELLO_THERE"] as const;
const ValidActionsSchema = z.enum(validActions);
const ParseableSchema = z.object({
action: z.string().transform((value, ctx) => {
const transformed = value.includes("_") ? value: camelToSnakeCase(value).toUpperCase();
const result = ValidActionsSchema.safeParse(transformed);
if (!result.success) {
result.error.issues.forEach((issue) => {
ctx.addIssue(issue);
});
return z.NEVER;
}
return result.data;
}),
});
export function parseAction(action: { action: string }) {
return ParseableSchema.parse(action);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment