-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConfigMap.ts
216 lines (202 loc) · 7.41 KB
/
ConfigMap.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import {buildOptions, ConfigOptions} from './ConfigOptions';
import {Err, Ok, Result} from '@luolapeikko/result-option';
import type {ILoggerLike, ISetOptionalLogger} from '@avanio/logger-like';
import {EnvMapSchema} from './types/EnvMapSchema';
import {getConfigObject} from './getConfigObject';
import {LoaderTypeValueStrict} from './types/TypeValue';
import {VariableError} from './VariableError';
/**
* TypeValueRecords
*/
export type TypeValueRecords<T> = Record<keyof T, LoaderTypeValueStrict<T[keyof T]>>;
/**
* ConfigMap
* @example
* type ConfigEnv = {
* PORT: number;
* HOST: string;
* DEBUG: boolean;
* URL: URL;
* };
* const config = new ConfigMap<ConfigEnv>({
* DEBUG: {loaders: [env()], parser: booleanParser, defaultValue: false},
* HOST: {loaders: [env()], parser: stringParser, defaultValue: 'localhost'},
* PORT: {loaders: [env()], parser: integerParser, defaultValue: 3000},
* URL: {loaders: [env()], parser: new UrlParser({urlSanitize: true}), defaultValue: new URL('http://localhost:3000')},
* });
* console.log('port', await config.get('PORT'));
*/
export class ConfigMap<Data extends Record<string, unknown>> implements ISetOptionalLogger {
private schema: EnvMapSchema<Data>;
private options: ConfigOptions;
/**
* ConfigMap constructor
* @param {EnvMapSchema<Data>} schema - schema of config map
* @param {ConfigOptions} options - optional config options (logger, namespace)
*/
constructor(schema: EnvMapSchema<Data>, options: ConfigOptions = {logger: undefined, namespace: undefined}) {
this.schema = schema;
this.options = options;
}
/**
* Set logger value
* @param {ILoggerLike | undefined} logger - logger like object
*/
public setLogger(logger: ILoggerLike | undefined): void {
this.options.logger = logger;
}
/**
* get env object from config map
* @returns {Promise<TypeValueRecords<Data>>} Promise of env object or undefined
* @example
* const valueObject: LoaderTypeValue<number> = await config.getObject('PORT');
* console.log(valueObject.type, valueObject.value); // 'env', 3000
*/
public async getObject<Key extends keyof Data = keyof Data>(key: Key): Promise<LoaderTypeValueStrict<Data[Key]>> {
const entry = this.schema[key];
if (!entry) {
throw new VariableError(`ConfigMap key ${String(key)} not found in config map`);
}
if (typeof key !== 'string') {
throw new VariableError(`ConfigMap key ${String(key)} is not a string`);
}
const {loaders, parser, defaultValue, params, undefinedThrowsError, undefinedErrorMessage} = entry;
const configObject = (await getConfigObject<Data[Key]>(key, loaders, parser, defaultValue, params, this.options)) as LoaderTypeValueStrict<Data[Key]>;
if (undefinedThrowsError && configObject.value === undefined) {
buildOptions(this.options).logger?.info(`ConfigMap key ${String(key)} is undefined (expect to throw error)`);
throw new VariableError(undefinedErrorMessage || `ConfigMap key ${String(key)} is undefined`);
}
return configObject;
}
/**
* get env object from config map as Result
* @returns {Promise<Result<TypeValueRecords<Data>>>} Result Promise of env object or undefined
* @example
* const valueObject: Result<LoaderTypeValue<number>> = await config.getObjectResult('PORT');
* if (valueObject.isOk()) {
* const {type, value} = valueObject.ok();
* console.log(type, value); // 'env', 3000
* }
*/
public async getObjectResult<Key extends keyof Data = keyof Data>(key: Key): Promise<Result<LoaderTypeValueStrict<Data[Key]>>> {
try {
return Ok(await this.getObject(key));
} catch (err) {
return Err(err);
}
}
/**
* get env value from config map
* @returns {Promise<Data[Key]>} Promise of value or undefined
* @example
* const port: number = await config.get('PORT');
*/
public async get<Key extends keyof Data = keyof Data>(key: Key): Promise<Data[Key]> {
return (await this.getObject(key)).value;
}
/**
* get env value as string from config map
* @returns {Promise<string | undefined>} Promise of string value or undefined
* @example
* const port: string = await config.getString('PORT');
*/
public async getString<Key extends keyof Data = keyof Data>(key: Key): Promise<undefined extends Data[Key] ? string | undefined : string> {
return (await this.getObject(key)).stringValue;
}
/**
* get env value from config map as Result
* @returns {Promise<Result<Data[Key]>>} Result Promise of value or undefined
* @example
* const port: Result<number> = await config.getResult('PORT');
* if (port.isOk()) {
* console.log('port', port.ok());
* }
*/
public async getResult<Key extends keyof Data = keyof Data>(key: Key): Promise<Result<Data[Key]>> {
try {
return Ok(await this.get(key));
} catch (err) {
return Err(err);
}
}
/**
* get env value as string from config map as Result
* @returns {Promise<Result<string | undefined>>} Result Promise of string value or undefined
* @example
* const port: Result<string> = await config.getStringResult('PORT');
* if (port.isOk()) {
* console.log('port', port.ok());
* }
*/
public async getStringResult<Key extends keyof Data = keyof Data>(key: Key): Promise<Result<undefined extends Data[Key] ? string | undefined : string>> {
try {
return Ok(await this.getString(key));
} catch (err) {
return Err(err);
}
}
/**
* get all env value objects from config map
* @returns {Promise<TypeValueRecords<Data>>} Promise of all values
* @example
* const values: TypeValueRecords<Data> = await config.getAll();
* console.log(values.PORT.type, values.PORT.value); // 'env', 3000
*/
public async getAllObjects(): Promise<TypeValueRecords<Data>> {
const values = await this.getAllPromises();
return values.reduce((result, [key, value]) => {
result[key] = value;
return result;
}, {} as TypeValueRecords<Data>);
}
/**
* get all env values from config map
* @returns {Promise<Data>} Promise of all values
* @example
* const values: Data = await config.getAllValues();
* console.log('PORT', values.PORT); // 3000 (number)
*/
public async getAllValues(): Promise<Data> {
const values = await this.getAllPromises();
return values.reduce((result, [key, value]) => {
result[key] = value.value;
return result;
}, {} as Data);
}
/**
* get all env values from config map as string
* @returns {Promise<Record<keyof Data, string>>} Promise of all values as string
* @example
* const values: Record<keyof Data, string> = await config.getAllStringValues();
* console.log('PORT', values.PORT); // '3000' (string)
*/
public async getAllStringValues(): Promise<Record<keyof Data, string>> {
const values = await this.getAllPromises();
return values.reduce<Record<keyof Data, string>>(
(result, [key, value]) => {
result[key] = value.stringValue;
return result;
},
{} as Record<keyof Data, string>,
);
}
/**
* Validate all env values from config map, expect to throw error if error exists
*
* @param callback callback function
*/
public async validateAll(callback: (data: Data) => void): Promise<void> {
const data = await this.getAllValues();
callback(data);
}
/**
* run lookup to all keys and return all promises
*/
private getAllPromises(): Promise<[keyof Data, LoaderTypeValueStrict<Data[keyof Data]>][]> {
return Promise.all(
(Object.keys(this.schema) as (keyof Data)[]).map<Promise<[keyof Data, LoaderTypeValueStrict<Data[keyof Data]>]>>(async (key) => {
return [key, await this.getObject(key as keyof Data)];
}),
);
}
}