Skip to content

Commit afbf6e2

Browse files
committed
fix(app): ensure already uppercased names stay the same
1 parent 4bea9fb commit afbf6e2

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

packages/app/src/app.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,17 @@ type EnvNamingStrategy =
4141
| ((name: string) => string | 'same' | 'upper' | 'lower' | undefined);
4242

4343
function camelToUpperCase(str: string) {
44-
return str.replace(/[A-Z]+/g, (letter: string) => `_${letter.toUpperCase()}`).toUpperCase();
44+
if (/^[A-Z0-9_]+$/.test(str)) return str; // already upper snake case
45+
return str
46+
.replace(/([a-z0-9])([A-Z])/g, '$1_$2') // insert underscore between lower/number and upper
47+
.toUpperCase();
4548
}
4649

4750
function camelToLowerCase(str: string) {
48-
return str.replace(/[A-Z]+/g, (letter: string) => `_${letter.toLowerCase()}`).toLowerCase();
51+
if (/^[a-z0-9_]+$/.test(str)) return str; // already lower snake case
52+
return str
53+
.replace(/([a-z0-9])([A-Z])/g, '$1_$2') // insert underscore
54+
.toLowerCase();
4955
}
5056

5157
function convertNameStrategy(namingStrategy: EnvNamingStrategy, name: string): string {

packages/app/tests/application.spec.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,24 @@ test('loadConfigFromEnvVariables', async () => {
5353
expect(baseService.db).toBe('changed2');
5454
});
5555

56+
test('loadConfigFromEnvVariables upper same', async () => {
57+
process.env.CC_PREVIEW_INTERNAL_KEY = 'abced';
58+
class Config {
59+
PREVIEW_INTERNAL_KEY: string = 'default';
60+
}
61+
62+
class Service {
63+
constructor(public key: Config['PREVIEW_INTERNAL_KEY']) {
64+
}
65+
}
66+
67+
const app = new App({ config: Config, providers: [Service] });
68+
app.loadConfigFromEnv({ prefix: 'CC_', namingStrategy: 'upper' });
69+
70+
const service = app.get(Service);
71+
expect(service.key).toBe('abced');
72+
});
73+
5674
test('loadConfigFromEnvFile', async () => {
5775
const app = new App({ config: Config, providers: [Service], imports: [new BaseModule] });
5876
app.loadConfigFromEnv({ envFilePath: dirname + '/test.env' });

0 commit comments

Comments
 (0)