Created
April 16, 2025 00:50
-
-
Save NuroDev/9258a15c0a2cb36742674f078eee48a6 to your computer and use it in GitHub Desktop.
π Zod - `X` or `X_FILE` transformer
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 { z } from 'zod'; | |
function transformFileProperty<T extends string>(key: T) { | |
return (data: Record<string, string>) => { | |
if (data[key]) { | |
return { | |
[key]: data[key], | |
} as { | |
[P in T]: string; | |
}; | |
} | |
if (data[`${key}_FILE`]) { | |
return { | |
[key]: Deno.readTextFileSync(data[`${key}_FILE`]).trim(), | |
} as { | |
[P in T]: string; | |
}; | |
} | |
throw new Error( | |
`Either \`${key}\` or \`${key}_FILE\` must be provided`, | |
); | |
}; | |
} | |
const MySchema = z | |
.object({ | |
MY_SECRET: z.string(), | |
MY_SECRET_FILE: z.string(), | |
}) | |
.partial() | |
.transform(transformFileProperty('MY_SECRET')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment