-
Notifications
You must be signed in to change notification settings - Fork 565
/
http-utils.ts
157 lines (145 loc) · 4.58 KB
/
http-utils.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
import type { IncomingMessage, ServerResponse } from 'node:http'
import { Readable } from 'stream'
import type { AddressInfo } from './types.js'
import type { Socket } from 'node:net'
import { isAsyncIterable } from '@graphql-tools/utils'
export interface NodeRequest {
protocol?: string
hostname?: string
body?: any
url?: string
method?: string
headers: any
req?: IncomingMessage
raw?: IncomingMessage
socket?: Socket
query?: any
}
function getRequestAddressInfo(
nodeRequest: NodeRequest,
defaultAddressInfo: AddressInfo,
): AddressInfo {
const hostname =
nodeRequest.hostname ||
nodeRequest.socket?.localAddress
?.split('ffff')
?.join('')
?.split(':')
?.join('') ||
nodeRequest.headers?.host?.split(':')[0] ||
defaultAddressInfo.hostname ||
'localhost'
const port = nodeRequest.socket?.localPort || defaultAddressInfo.port || 80
return {
protocol: (nodeRequest.protocol ||
defaultAddressInfo.protocol ||
'http') as 'http',
hostname,
endpoint: nodeRequest.url || defaultAddressInfo.endpoint,
port,
}
}
function buildFullUrl(addressInfo: AddressInfo) {
return `${addressInfo.protocol}://${addressInfo.hostname}:${addressInfo.port}${addressInfo.endpoint}`
}
function configureSocket(rawRequest: NodeRequest) {
rawRequest?.socket?.setTimeout?.(0)
rawRequest?.socket?.setNoDelay?.(true)
rawRequest?.socket?.setKeepAlive?.(true)
}
export function getNodeRequest(
nodeRequest: NodeRequest,
defaultAddressInfo: AddressInfo,
RequestCtor: typeof Request,
): Request {
const rawRequest = nodeRequest.raw || nodeRequest.req || nodeRequest
configureSocket(rawRequest)
const addressInfo = getRequestAddressInfo(rawRequest, defaultAddressInfo)
const fullUrl = buildFullUrl(addressInfo)
if (nodeRequest.query) {
const urlObj = new URL(fullUrl)
for (const queryName in nodeRequest.query) {
const queryValue = nodeRequest.query[queryName]
urlObj.searchParams.set(queryName, queryValue)
}
}
const baseRequestInit: RequestInit = {
method: nodeRequest.method,
headers: nodeRequest.headers,
}
if (nodeRequest.method !== 'POST') {
return new RequestCtor(fullUrl, baseRequestInit)
}
/**
* Some Node server frameworks like Serverless Express sends a dummy object with body but as a Buffer not string
* so we do those checks to see is there something we can use directly as BodyInit
* because the presence of body means the request stream is already consumed and,
* rawRequest cannot be used as BodyInit/ReadableStream by Fetch API in this case.
*/
const maybeParsedBody = nodeRequest.body
if (maybeParsedBody != null && Object.keys(maybeParsedBody).length > 0) {
if (
typeof maybeParsedBody === 'string' ||
maybeParsedBody[Symbol.toStringTag] === 'Uint8Array' ||
maybeParsedBody[Symbol.toStringTag] === 'Blob' ||
maybeParsedBody[Symbol.toStringTag] === 'FormData' ||
maybeParsedBody[Symbol.toStringTag] === 'URLSearchParams' ||
isAsyncIterable(maybeParsedBody)
) {
return new RequestCtor(fullUrl, {
...baseRequestInit,
body: maybeParsedBody as any,
})
}
const request = new RequestCtor(fullUrl, {
...baseRequestInit,
})
if (!request.headers.get('content-type')?.includes('json')) {
request.headers.set('content-type', 'application/json')
}
return new Proxy(request, {
get: (target, prop: keyof Request, receiver) => {
switch (prop) {
case 'json':
return async () => maybeParsedBody
default:
return Reflect.get(target, prop, receiver)
}
},
})
}
return new RequestCtor(fullUrl, {
headers: nodeRequest.headers,
method: nodeRequest.method,
body: rawRequest as any,
})
}
function isReadable(responseBody: any): responseBody is Readable {
return !!responseBody.pipe
}
export function sendNodeResponse(
{ headers, status, statusText, body }: Response,
serverResponse: ServerResponse,
) {
headers.forEach((value, name) => {
serverResponse.setHeader(name, value)
})
serverResponse.statusCode = status
serverResponse.statusMessage = statusText
return new Promise<void>((resolve) => {
if (body == null) {
serverResponse.end(resolve)
return
}
if (body[Symbol.toStringTag] === 'Uint8Array') {
serverResponse.end(body, resolve)
return
}
const nodeStream = isReadable(body) ? body : Readable.from(body)
nodeStream.once('end', resolve)
serverResponse.once('close', () => {
nodeStream.destroy()
})
nodeStream.pipe(serverResponse)
})
}