-
-
Notifications
You must be signed in to change notification settings - Fork 184
/
resolve-config.ts
58 lines (51 loc) · 1.86 KB
/
resolve-config.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import camelCase from 'camelcase';
import finder from 'find-package-json';
import debug from 'debug';
const log = debug('MongoMS:ResolveConfig');
const ENV_CONFIG_PREFIX = 'MONGOMS_';
const defaultValues = new Map<string, string>();
/**
* Set an Default value for an specific key
* Mostly only used internally (for the "global-x.x" packages)
* @param key The Key the default value should be assigned to
* @param value The Value what the default should be
*/
export function setDefaultValue(key: string, value: string): void {
defaultValues.set(key, value);
}
let packageJsonConfig: {
[key: string]: string;
} = {};
/**
* Find the nearest package.json for the provided directory
* @param directory Set an custom directory to search the config in (default: process.cwd())
*/
export function findPackageJson(directory?: string): void {
const finderIterator = finder(directory || process.cwd()).next();
log(`Using package.json at "${finderIterator.filename}"`);
packageJsonConfig = finderIterator.value?.config?.mongodbMemoryServer ?? {};
}
export const reInitializePackageJson = findPackageJson; // TODO: remove this line on next minor version
findPackageJson();
/**
* Resolve "variableName" with a prefix of "ENV_CONFIG_PREFIX"
* @param variableName The variable to use
*/
export default function resolveConfig(variableName: string): string | undefined {
return (
process.env[`${ENV_CONFIG_PREFIX}${variableName}`] ??
packageJsonConfig?.[camelCase(variableName)] ??
defaultValues.get(variableName)
);
}
/**
* Convert "1, on, yes, true" to true (otherwise false)
* @param env The String / Environment Variable to check
*/
export function envToBool(env: string = ''): boolean {
return ['1', 'on', 'yes', 'true'].indexOf(env.toLowerCase()) !== -1;
}
// enable debug if "MONGOMS_DEBUG" is true
if (envToBool(resolveConfig('DEBUG'))) {
debug.enable('MongoMS:*');
}