Skip to content

Instantly share code, notes, and snippets.

@NuroDev
Created April 16, 2025 00:50
Show Gist options
  • Save NuroDev/9258a15c0a2cb36742674f078eee48a6 to your computer and use it in GitHub Desktop.
Save NuroDev/9258a15c0a2cb36742674f078eee48a6 to your computer and use it in GitHub Desktop.
πŸ’Ž Zod - `X` or `X_FILE` transformer
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