-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
request.ts
103 lines (92 loc) · 3.04 KB
/
request.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
import type { IncomingMessage } from 'http'
import type Https from 'https'
import type { RequestInit, Response } from 'node-fetch'
import type { O } from 'ts-toolbelt'
import { NetworkError } from '../errors/NetworkError'
import { getJSRuntimeName } from './getJSRuntimeName'
// our implementation handles less
export type RequestOptions = O.Patch<{ headers?: { [k: string]: string }; body?: string }, RequestInit>
export type RequestResponse = O.Required<O.Optional<Response>, 'json' | 'url' | 'ok' | 'status'>
// fetch is global on edge runtime
declare let fetch: typeof nodeFetch
/**
* Isomorphic `fetch` that imitates `fetch` via `https` when on Node.js.
* @param url
* @param options
* @returns
*/
export async function request(
url: string,
options: RequestOptions & { clientVersion: string },
): Promise<RequestResponse> {
const jsRuntimeName = getJSRuntimeName()
try {
if (jsRuntimeName === 'browser') {
return await fetch(url, options)
} else {
return await nodeFetch(url, options)
}
} catch (e) {
throw new NetworkError({ clientVersion: options.clientVersion })
}
}
/**
* Build http headers from fetch-like headers
* @param options
* @returns
*/
function buildHeaders(options: RequestOptions): RequestOptions['headers'] {
return {
...options.headers,
'Content-Type': 'application/json',
}
}
/**
* Build http options from fetch-like options
* @param options
* @returns
*/
function buildOptions(options: RequestOptions): Https.RequestOptions {
return {
method: options.method,
headers: buildHeaders(options),
}
}
/**
* Build a fetch-like response from an http response
* @param incomingData
* @param response
* @returns
*/
function buildResponse(incomingData: Buffer[], response: IncomingMessage): RequestResponse {
return {
json: () => JSON.parse(Buffer.concat(incomingData).toString()),
ok: response.statusCode! >= 200 && response.statusCode! < 300,
status: response.statusCode!,
url: response.url!,
}
}
/**
* Imitates `fetch` via `https` to only suit our needs, it does nothing more.
* This is because we cannot bundle `node-fetch` as it uses many other Node.js
* utilities, while also bloating our bundles. This approach is much leaner.
* @param url
* @param options
* @returns
*/
async function nodeFetch(url: string, options: RequestOptions = {}): Promise<RequestResponse> {
const https: typeof Https = await globalThis[['e', 'v', 'a', 'l'].join('')](`import('https')`)
const httpsOptions = buildOptions(options)
const incomingData = [] as Buffer[]
return new Promise((resolve, reject) => {
// we execute the https request and build a fetch response out of it
const request = https.request(url, httpsOptions, (response) => {
response.on('data', (chunk: Buffer) => incomingData.push(chunk))
response.on('end', () => resolve(buildResponse(incomingData, response)))
response.on('error', reject)
})
request.on('error', reject) // handle errors
request.write(options.body ?? '') // http body data
request.end() // flush & send
})
}