-
Notifications
You must be signed in to change notification settings - Fork 0
/
read-config.ts
87 lines (75 loc) · 2.2 KB
/
read-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
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
import { IncomingMessage } from 'http';
import { ServerHttp2Stream } from 'http2';
import * as path from 'path';
import { URL } from 'url';
import { asDefinedOr, foldDict, appendToArray, insteadDefinedOr } from './utils';
export type ResponseHandler = (
response: IncomingMessage,
stream: ServerHttp2Stream,
) => Promise<void>;
export interface Config {
readonly port?: number;
readonly staticBase?: string;
readonly proxyTo?: string;
readonly proxy?: {
[path: string]: {
auth?: 'ntlm',
responseHandler?: ResponseHandler,
},
},
}
interface ProxySettings {
readonly path: RegExp;
readonly auth: 'ntlm' | null;
readonly responseHandler: ResponseHandler | undefined;
}
export interface Settings {
readonly port: number;
readonly staticBase: string;
readonly proxyProtocol: string;
readonly proxyHost: string;
readonly proxyPort: number;
readonly proxy: ProxySettings[];
}
function loadConfig(
moduleName: string,
): Config {
let config = {} as Config;
try {
config = require(moduleName);
} catch (e) {
config = {};
}
return config;
}
export function readSettings(
moduleName: string,
): Settings {
const config = loadConfig(moduleName);
const port = asDefinedOr(config.port, 9000);
const staticBase = path.join(__dirname, asDefinedOr(config.staticBase, './'));
const proxyTo = insteadDefinedOr(config.proxyTo, url => new URL(url), null);
const proxyProtocol = insteadDefinedOr(proxyTo, url => url.protocol, 'http:')
const proxyHost = insteadDefinedOr(proxyTo, url => url.hostname, 'example.com');
const proxyPort = insteadDefinedOr(proxyTo, url => parseInt(url.port), 80);
const proxy = foldDict(
asDefinedOr(config.proxy, {}),
[] as ProxySettings[],
(key, value, result) => appendToArray(
result,
{
path: new RegExp(key),
auth: asDefinedOr(value.auth, null),
responseHandler: value.responseHandler,
},
),
);
return {
port,
staticBase,
proxyProtocol,
proxyHost,
proxyPort,
proxy,
};
}