-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlib.ts
More file actions
87 lines (75 loc) · 2.62 KB
/
Copy pathlib.ts
File metadata and controls
87 lines (75 loc) · 2.62 KB
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 http from 'http';
import https from 'https';
export interface Configs {
[pipe: string]: string | undefined;
}
export type Callback = (value?: any) => void;
function tatler<T extends Configs, K extends keyof T> (config: T, pipe?: K | boolean, throwError = true) {
const keys = Object.keys(config);
if (typeof pipe === 'boolean') {
throwError = pipe;
pipe = undefined;
} else if (typeof pipe === 'string') {
if (!config[pipe] && throwError) {
throw new Error(`No secret for pipe ${pipe} in given config.`);
}
return (message: string, clb?: Callback) => tatler.doRequest(pipe as string, config[pipe as K], message, clb, throwError);
}
return (pipe: K | string, message?: string | Callback, clb?: Callback) => {
if (!clb && keys.length === 1 && (!message || typeof message === 'function')) {
clb = message as Callback;
message = pipe as string;
pipe = keys[0];
}
return tatler.doRequest(pipe as string, config[pipe], message as string, clb, throwError);
};
}
function doRequest (pipe: string, secret: string | undefined, message: string, clb: Callback | undefined, throwError: boolean) {
let value = Promise.resolve();
if (secret) {
pipe = encodeURIComponent(pipe);
secret = encodeURIComponent(secret);
let limit = 4000;
do {
const encoded = encodeURIComponent(message.substr(0, limit));
if (encoded.length > 6144) {
limit -= 100;
continue;
}
message = encoded;
break;
} while (limit > 0);
const options = {
host: process.env.TATLER_CLIENT_HOST ? process.env.TATLER_CLIENT_HOST : 'tatler.jsbot.eu',
path: `/msg/${pipe}/${secret}/?${message}`,
port: process.env.TATLER_CLIENT_PORT ?? (process.env.TATLER_PREFER_HTTP ? 80 : 443),
timeout: 5000
};
value = new Promise((resolve, reject) => {
(process.env.TATLER_PREFER_HTTP ? http : https).request(options, (res) => {
let str = '';
res.on('data', (chunk) => {
str += chunk;
}).on('end', () => {
if (str === 'scheduled' && res.statusCode === 200) {
resolve();
} else {
reject(new Error(`HTTP${res.statusCode}: ${str}`));
}
});
}).on('error', (err) => {
console.error(`Error happened while sending tatler.jsbot.eu notification: ${err.message}`);
reject(err.message);
}).end();
});
} else if (throwError) {
throw new Error(`No secret for pipe ${pipe} in given config.`);
}
if (clb) {
return value.then(clb, clb);
} else {
return value;
}
}
tatler.doRequest = doRequest;
export default tatler;