-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
176 lines (158 loc) · 5.26 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
/**
* ### esm
*
* ```js
* import { node } from '@paychex/adapter-node';
* ```
*
* ### cjs
*
* ```js
* const { node } = require('@paychex/adapter-node');
* ```
*
* @module main
*/
import * as https from 'https';
import {
get,
set,
filter,
flatten,
isEmpty,
isString,
merge,
attempt,
} from 'lodash';
import type { HeadersMap, Request, Response } from '@paychex/core/types/data';
export type { Request, Response };
type Header = Record<string, string>;
const XSSI = /^\)]\}',?\n/;
const SUCCESS = /^2\d\d$/;
function safeParseJSON(response: Response): void {
const json = String(response.data);
response.data = JSON.parse(json.replace(XSSI, ''));
}
function setCached(response: Response, sendDate: Date): void {
const date = new Date(get(response, 'meta.headers.date') as string);
if (!isNaN(Number(date))) { // determines if Date is valid
// Date header is only accurate to the nearest second
// so we round both down to the second before comparing
const responseTime = Math.floor(date.getTime() / 1000);
const requestTime = Math.floor(sendDate.getTime() / 1000);
set(response, 'meta.cached', responseTime < requestTime);
}
}
function setErrorFromStatus(response: Response): void {
const hasError = get(response, 'meta.error', false);
const isFailure = !SUCCESS.test(String(get(response, 'status', 0)));
set(response, 'meta.error', hasError || isFailure);
}
function toStringArray(value: string | string[]): string {
return filter(flatten([value]), isString).join(', ');
}
function toKeyValuePair(name: string): [string, string] {
return [name, toStringArray(this[name])];
}
function hasHeaderValue([, values]: [any, string]): boolean {
return !isEmpty(values);
}
function setHeaderValue(result: Header, [name, value]: [string, string]): Header {
result[name] = value;
return result;
}
function transformHeaders(headers: HeadersMap): Header {
return Object.keys(headers)
.map(toKeyValuePair, headers)
.filter(hasHeaderValue)
.reduce(setHeaderValue, Object.create(null));
}
async function parseData(type: XMLHttpRequestResponseType, response: Response) {
switch (String(type).toLowerCase()) {
case '':
case 'json':
attempt(safeParseJSON, response);
break;
case 'arraybuffer':
response.data = new Uint8Array(response.data.split(' '));
break;
case 'blob':
response.data = null;
response.meta.error = true;
response.statusText = 'Type `Blob` does not exist in NodeJS.';
break;
case 'document':
const parser = new DOMParser();
const responseType = get(response, 'meta.headers.content-type', 'text/html');
response.data = parser.parseFromString(response.data, responseType as DOMParserSupportedType);
break;
}
}
/**
* A data adapter that uses the NodeJS built-in [https](https://nodejs.org/api/https.html) library to convert a Request into a Response. Can be passed to the [@paychex/core](https://github.com/paychex/core) createDataLayer factory method to enable data operations on NodeJS.
*
* @param request The Request to convert into a Response.
* @returns A Promise resolved with the Response.
* @example
* ```js
* const proxy = data.createProxy();
* const { createRequest, fetch, setAdapter } = data.createDataLayer(proxy, node);
* ```
*/
export function node(request: Request): Promise<Response> {
const response: Response = {
meta: {
headers: {},
messages: [],
error: false,
cached: false,
timeout: false,
},
data: null,
status: 0,
statusText: 'Unknown',
};
return new Promise(function RequestPromise(resolve) {
let body = '';
const sendDate = new Date();
const options: https.RequestOptions = {
method: request.method,
timeout: request.timeout || 2147483647,
headers: transformHeaders(request.headers),
};
const req = https.request(request.url, options, function callback(res) {
merge(response.meta.headers, res.headers);
setCached(response, sendDate);
response.status = res.statusCode;
response.statusText = res.statusMessage;
res.setEncoding('utf8');
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', async () => {
response.data = body;
await parseData(request.responseType, response);
setErrorFromStatus(response);
resolve(response);
});
});
req.on('error', (e) => {
response.meta.error = true;
response.meta.messages = [{
data: [],
code: e.message,
severity: 'ERROR',
}];
});
req.on('timeout', () => {
response.meta.error = true;
response.meta.timeout = true;
});
req.on('abort', () => {
response.meta.error = true;
});
if (request.body != null)
req.write(JSON.stringify(request.body));
req.end();
});
}