Created
April 1, 2025 21:55
-
-
Save josephdburdick/42f05b9bb881de1af25880a7ba9e2b9c to your computer and use it in GitHub Desktop.
Underscores to camelCase conversion and type inference (camelcase-keys, zod)
This file contains 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 { z } from "zod" | |
import camelcaseKeys from "camelcase-keys" | |
export const SceneSchema = z | |
.object({ | |
id: z.string().optional(), | |
movieId: z.string(), | |
type: z.string(), | |
}) | |
.transform((item) => { | |
return { | |
...item, | |
toJson: () => { | |
return Object.fromEntries( | |
Object.entries(item).map(([key, value]) => [ | |
key.replace(/([A-Z])/g, "_$1").toLowerCase(), | |
value, | |
]), | |
) | |
}, | |
} | |
}) | |
export type Scene = z.infer<typeof SceneSchema> & { | |
toJson(): Object | |
} | |
export const createScene = (data: Record<string, unknown>): Scene => { | |
return SceneSchema.parse(camelcaseKeys(data, { deep: true })) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment