-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
277 lines (249 loc) · 7.7 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
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
/**
* Useful for generic functions that need to extend from objects.
*/
export interface ObjectLiteral {
[key: string]: any;
}
/**
* Breaks an array into specified chunk sizes.
* @param array The array to break apart.
* @param chunkSize What size the chunks should be.
* @returns Returns an array of arrays.
*/
export function chunkArray<T>(array: T[], chunkSize: number): T[][] {
const results: T[][] = [];
const arrayClone = array.slice();
const numOfChunks = Math.ceil(arrayClone.length / chunkSize);
for (let i = 0; i < numOfChunks; i++) {
results.push(arrayClone.splice(0, chunkSize));
}
return results;
}
/**
* Gets the environment variable or throws an error.
* @param name Name of the env variable.
* @returns Returns the value of the env variable.
*/
export function getEnvVarOrThrow(name: string): string {
return getOrThrow(() => process.env[name], `ENV variable: ${name} is not set!`);
}
export function pipe<A, B>(value: A, f1: (value: A) => B): B;
export function pipe<A, B, C>(value: A, f1: (value: A) => B, f2: (value: B) => C): C;
export function pipe<A, B, C, D>(value: A, f1: (value: A) => B, f2: (value: B) => C, f3: (value: C) => D): D;
export function pipe<A, B, C, D, E>(
value: A,
f1: (value: A) => B,
f2: (value: B) => C,
f3: (value: C) => D,
f4: (value: D) => E
): E;
export function pipe<A, B, C, D, E, F>(
value: A,
f1: (value: A) => B,
f2: (value: B) => C,
f3: (value: C) => D,
f4: (value: D) => E,
f5: (value: E) => F
): F;
export function pipe<A, B, C, D, E, F, G>(
value: A,
f1: (value: A) => B,
f2: (value: B) => C,
f3: (value: C) => D,
f4: (value: D) => E,
f5: (value: E) => F,
f6: (value: F) => G
): G;
/**
* Transforms a value to another value.
* @param value The value to transform.
* @param mapFunc The transform function.
* @returns Returns the new value.
*/
export function pipe<T, U>(value: T, ...mapFuncs: ((value: any) => any)[]): U {
// @ts-ignore
return mapFuncs.reduce((newValue, mapFunc) => mapFunc(newValue), value);
}
export function pipeSafely<A, B>(value: A | null | undefined, f1: (value: A) => B): B | undefined;
export function pipeSafely<A, B, C>(
value: A | null | undefined,
f1: (value: A) => B,
f2: (value: B) => C
): C | undefined;
export function pipeSafely<A, B, C, D>(
value: A | null | undefined,
f1: (value: A) => B,
f2: (value: B) => C,
f3: (value: C) => D
): D | undefined;
export function pipeSafely<A, B, C, D, E>(
value: A | null | undefined,
f1: (value: A) => B,
f2: (value: B) => C,
f3: (value: C) => D,
f4: (value: D) => E
): E | undefined;
export function pipeSafely<A, B, C, D, E, F, G>(
value: A | null | undefined,
f1: (value: A) => B,
f2: (value: B) => C,
f3: (value: C) => D,
f4: (value: D) => E,
f5: (value: E) => F,
f6: (value: F) => G
): G | undefined;
/**
* Transforms a possibly undefined value to another value.
* @param value The value to transform.
* @param mapFunc The transform function.
* @returns Returns the new possibly undefined value.
*/
export function pipeSafely<T, U>(value: T | null | undefined, ...mapFuncs: ((value: any) => any)[]): U | undefined {
if (notEmpty(value)) {
// @ts-ignore
return pipe(
value,
...mapFuncs
);
}
}
/**
* Gets the possibly undefined value from the callback.
* If the callback throws an error, then returns undefined.
* Useful when accessing a dangerous interface or 'any'.
* @param getCb Callback that accesses the value.
* @returns Returns the value or undefined.
*/
export function getSafely<T>(getCb: () => T | undefined): T | undefined {
let result;
try {
result = getCb();
} finally {
return result;
}
}
/**
* Gets the possibly undefined value from the callback.
* If the callback throws an error or returns undefined, then throws an error.
* Useful when accessing a dangerous interface or 'any' that's mandatory.
* @param getCb Callback that accesses the value.
* @param errorMessage The error message to throw if undefined.
* @returns Returns the value.
*/
export function getOrThrow<T>(getCb: () => T | undefined, errorMessage: string = 'getOrThrow - undefined value!'): T {
const result = getSafely(getCb);
if (result === undefined) {
throw new Error(errorMessage);
}
return result;
}
/**
* Gets the possibly undefined value from the callback.
* If the callback throws an error, then returns the provided default value.
* Useful when accessing a dangerous interface or 'any'.
* @param getCb Callback that accesses the value.
* @param defaultValue Fallback value if the callback errors or returns undefined.
* @returns Returns the callback value or the default value.
*/
export function getOrElse<T>(getCb: () => T | undefined, defaultValue: T): T {
let result = getSafely(getCb);
if (result === undefined) {
result = defaultValue;
}
return result;
}
/**
* Polyfill for flatten.
* @param nestedArrays The array of arrays to flatten
* @returns Returns the flattened array.
*/
export function flatten<T>(nestedArrays: T[][]): T[] {
return ([] as T[]).concat(...nestedArrays);
}
/**
* Checks if a value is defined, in a type-safe way.
* Useful for filtering through arrays.
* @param value The value to check.
* @returns Returns true/false if the value is defined.
*/
export function notEmpty<T>(value: T | null | undefined): value is T {
return value !== null && value !== undefined;
}
/**
* Checks if a value is plain old javascript object.
* @param value The value to check.
* @returns Returns true/false if the value is a POJO.
*/
export function isPlainObject(value: any): value is Object {
return typeof value === 'object' && value.constructor === Object;
}
/**
* Initializes a class and copies over additional properties.
* @param entityClass The class to initialize.
* @param partials The properties to copy over to the new object.
* @returns Returns the new instance.
*/
export function initAndSetProps<T extends ObjectLiteral>(entityClass: { new (): T }, ...partials: Partial<T>[]): T {
const entity = new entityClass();
return Object.assign(entity, ...partials);
}
/**
* Node.js utility functions.
*/
/**
* Starts a Node.js app with the cluster module
* @param initCb The callback that starts the app.
*/
export function startAppWithCluster(initCb: () => void): void {
const cluster = require('cluster');
if (cluster.isMaster) {
let cpuCount;
if (process.env.NODE_ENV === 'production') {
console.info('Running in production mode!');
cpuCount = require('os').cpus().length;
} else {
console.warn("Running in development mode, set NODE_ENV to 'production' for multi-core support.");
cpuCount = 1;
}
for (let i = 0; i < cpuCount; i++) {
cluster.fork();
}
cluster.on('exit', (worker: any) => {
console.error('Worker %d died :(', worker.id);
cluster.fork();
});
} else {
initCb();
}
}
/**
* Parses a database connection string into easier pieces.
* Only useable in Node.js environments.
* @param connectionString Connection string like 'postgres://USER:PASSWORD@DATABASE_URL/DATABASE_NAME'.
* @returns Returns an object with the connection data.
*/
export function parseConnectionString(
connectionString: string
): {
database: string;
host: string;
port: number;
ssl: boolean;
username: string;
password: string;
} {
const params = require('url').parse(connectionString, true);
params.pathname = params.pathname || '';
params.hostname = params.hostname || '';
params.port = params.port || '';
params.auth = params.auth || '';
const auth = params.auth.split(':');
return {
database: params.pathname.split('/')[1],
host: params.hostname,
port: parseInt(params.port, 10),
ssl: !!params.query.ssl,
username: auth[0],
password: auth[1]
};
}