Last active
February 27, 2024 20:53
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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