Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"Finished" prefix/case stuff #15

Merged
merged 5 commits into from
Dec 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/breezy-nails-happen.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@arundo/typed-env': patch
---

Add ability to remove prefixes from environment variables + types
21 changes: 21 additions & 0 deletions src/casings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
export type NamingConvention = 'camelcase' | 'pascalcase' | 'kebabcase' | 'default';

export type SnakeToCamelCase<S extends string> = S extends `${infer T}_${infer U}`
? `${Lowercase<T>}${Capitalize<SnakeToCamelCase<U>>}`
: Lowercase<S>;

export type SnakeToPascalCase<S extends string> = S extends `${infer T}_${infer U}`
? `${Capitalize<Lowercase<T>>}${SnakeToPascalCase<U>}`
: Capitalize<Lowercase<S>>;

export type SnakeToKebabCase<S extends string> = S extends `${infer T}_${infer U}`
? `${Lowercase<T>}-${Lowercase<SnakeToKebabCase<U>>}`
: Lowercase<S>;

export type ChangeCase<T extends NamingConvention, S extends string> = T extends 'camelcase'
? SnakeToCamelCase<S>
: T extends 'pascalcase'
? SnakeToPascalCase<S>
: T extends 'kebabcase'
? SnakeToKebabCase<S>
: S;
94 changes: 52 additions & 42 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,46 @@
import { z } from 'zod';
import { ChangeCase, NamingConvention } from './casings';

type SnakeToCamelCase<S extends string> = S extends `${infer T}_${infer U}`
? `${Lowercase<T>}${Capitalize<SnakeToCamelCase<U>>}`
: Lowercase<S>;

type RemovePrefix<P extends string | undefined, S extends string> = P extends string
? S extends `${P}_${infer U}`
type RemovePrefix<P extends string, S extends string> = P extends ''
? S
: P extends `${infer O}_`
? S extends `${O}_${infer U}`
? U
: S
: S extends `${P}_${infer U}`
? U
: S;

type OutputType<InputType, P extends string | undefined, T extends string> = {
[K in keyof InputType as T extends 'camelcase'
? SnakeToCamelCase<RemovePrefix<P, string & K>>
: RemovePrefix<P, string>]: InputType[K];
} & {};

type NamingConvention = 'camelcase' | 'default';

type BaseSchema = Record<string, unknown>;

type EnvReturnType<T extends string, P extends string | undefined, S extends BaseSchema> = T extends 'camelcase'
? OutputType<S, P, T>
: S;
type EnvReturnType<TCase extends NamingConvention, P extends string, S extends BaseSchema> = {
[K in keyof S as ChangeCase<TCase, RemovePrefix<P, string & K>>]: S[K];
} & {};

const toCamelCase = <TSchema extends BaseSchema>(str: string & keyof TSchema): string =>
str.toLowerCase().replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());

const toPascalCase = <TSchema extends BaseSchema>(str: string & keyof TSchema): string =>
str.toLowerCase().replace(/(^[a-z]|_[a-z])/g, (_, letter) => {
return letter.startsWith('_') ? letter.replace('_', '').toUpperCase() : letter.toUpperCase();
});

const toKebabCase = <TSchema extends BaseSchema>(str: string & keyof TSchema): string =>
str.toLowerCase().replace(/_/g, '-');

const getTransformFn = <TSchema extends BaseSchema>(transform: NamingConvention) => {
switch (transform) {
case 'camelcase':
return toCamelCase;
case 'pascalcase':
return toPascalCase;
case 'kebabcase':
return toKebabCase;
default:
return (str: string & keyof TSchema) => str;
}
};

const transformKeys =
<TSchema extends BaseSchema>(transformFn: (str: keyof TSchema) => keyof TSchema) =>
(obj: TSchema) =>
Expand All @@ -48,47 +62,43 @@ const getEnvironment = () => {
};

const removePrefix =
(prefix: string) =>
(prefix?: string) =>
<TSchema extends BaseSchema>(str: string & keyof TSchema): string =>
str.replace(prefix, '');
prefix ? (prefix.endsWith('_') ? str.replace(prefix, '') : str.replace(`${prefix}_`, '')) : str;

const removePrefixDecorator =
(prefix: string) =>
(prefix?: string) =>
(transform: <TSchema extends BaseSchema>(str: string & keyof TSchema) => string) =>
<TSchema extends BaseSchema>(str: string & keyof TSchema): string =>
transform(removePrefix(prefix)(str));

interface Options<TTransform> {
type Options<TTransform, TPrefixRemoval> = {
transform?: TTransform;
formatErrorFn?: (error: z.ZodError) => string;
excludePrefix?: string;
}
excludePrefix?: TPrefixRemoval;
};

export const typeEnvironment = <TSchema extends BaseSchema, TTransform extends NamingConvention = 'default'>(
export const typeEnvironment = <
TSchema extends BaseSchema,
TTransform extends NamingConvention = 'default',
TPrefixRemoval extends string = '',
>(
schema: z.Schema<TSchema>,
options: Options<TTransform> = {
transform: 'default' as TTransform,
formatErrorFn: formatError,
excludePrefix: '',
},
{
transform = 'default' as TTransform,
formatErrorFn = formatError,
excludePrefix = '' as TPrefixRemoval,
}: Options<TTransform, TPrefixRemoval> = {},
overrideEnv: Record<string, string | undefined> = getEnvironment(),
) => {
const { transform = 'default', formatErrorFn = formatError } = options ?? {};
const prefix = options?.excludePrefix ?? '';
const removePrefixWrapper = removePrefixDecorator(prefix);
const removePrefixWrapper = removePrefixDecorator(excludePrefix);
try {
return schema
const returnobj = schema
.transform((obj: TSchema) => {
if (transform === 'camelcase') {
return transformKeys(removePrefixWrapper(toCamelCase))(obj);
}
return obj;
return transformKeys(removePrefixWrapper(getTransformFn(transform)))(obj);
})
.parse(overrideEnv) as EnvReturnType<
NonNullable<typeof options.transform>,
typeof options.excludePrefix,
TSchema
>;
.parse(overrideEnv) as EnvReturnType<NonNullable<typeof transform>, NonNullable<typeof excludePrefix>, TSchema>;
return returnobj;
} catch (error) {
if (error instanceof z.ZodError) {
throw new Error(formatErrorFn(error));
Expand Down
12 changes: 12 additions & 0 deletions test/load.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,18 @@ test('transform camelcase', () => {
expect(env.databaseUrlTest).toEqual('postgres://localhost:5432/test');
});

test('transform kebab case', () => {
const env = typeEnvironment(
z.object({
PORT: z.string(),
DATABASE_URL_TEST: z.string(),
}),
{ transform: 'kebabcase' },
overrideEnv,
);
expect(env['database-url-test']).toEqual('postgres://localhost:5432/test');
});

test('remove vite prefix (camelcase)', () => {
const env = typeEnvironment(
z.object({
Expand Down