generated from vatsal2210/nodejs-typescript-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
71 lines (64 loc) 路 1.85 KB
/
index.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
59
60
61
62
63
64
65
66
67
68
69
70
71
import {
cosmiconfig,
cosmiconfigSync,
Options,
OptionsSync,
} from 'cosmiconfig';
import { config as dotenvConfig } from 'dotenv';
import { camelCase } from 'lodash';
import { CosmiconfigResult } from 'cosmiconfig/dist/types';
dotenvConfig();
export interface CosmicResult {
[index: string]: any;
}
const defaultSearchPlaces = (name: string) => [
'package.json',
`.${name}rc`,
`.${name}rc.json`,
`.${name}rc.yaml`,
`.${name}rc.yml`,
`.${name}rc.js`,
`.${name}`,
`.${name}.json`,
`.${name}.yaml`,
`.${name}.yml`,
`.${name}.js`,
`${name}.config.js`,
];
const _getCosmicResult = (result: CosmiconfigResult): CosmicResult => {
const env = { ...process.env };
for (const key in env) {
env[camelCase(key)] = env[key];
delete env[key];
}
return { ...(result || {}).config, ...env };
};
let cachedConfig: CosmicResult | undefined = undefined;
export const cosmic = async (name: string, options?: Options) => {
const { search } = cosmiconfig(name, {
searchPlaces: defaultSearchPlaces(name),
...options,
});
if (!cachedConfig) cachedConfig = _getCosmicResult(await search());
return cachedConfig;
};
let cachedConfigSync: CosmicResult | undefined = undefined;
export const cosmicSync = (name: string, options?: OptionsSync) => {
const { search } = cosmiconfigSync(name, {
searchPlaces: defaultSearchPlaces(name),
...options,
});
if (!cachedConfigSync) cachedConfigSync = _getCosmicResult(search());
return cachedConfigSync;
};
export const clearCosmicCache = () => {
dotenvConfig();
cachedConfig = undefined;
cachedConfigSync = undefined;
};
export const config = <T = any>(key: string, defaultValue?: T): T => {
if (cachedConfig && cachedConfig[key]) return cachedConfig[key] as T;
if (cachedConfigSync && cachedConfigSync[key])
return cachedConfigSync[key] as T;
return defaultValue as T;
};