forked from vercel/next.js
/
base-http.ts
264 lines (205 loc) · 6.53 KB
/
base-http.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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import type { ServerResponse, IncomingMessage, IncomingHttpHeaders } from 'http'
import type { Writable, Readable } from 'stream'
import { PERMANENT_REDIRECT_STATUS } from '../shared/lib/constants'
// import { ParsedNextUrl, parseNextUrl } from '../shared/lib/router/utils/parse-next-url'
import { getCookieParser, NextApiRequestCookies, parseBody } from './api-utils'
import { I18NConfig } from './config-shared'
import { NEXT_REQUEST_META, RequestMeta } from './request-meta'
export interface BaseNextRequestConfig {
basePath: string | undefined
i18n?: I18NConfig
trailingSlash?: boolean | undefined
}
export abstract class BaseNextRequest<Body = any> {
protected _cookies: NextApiRequestCookies | undefined
public abstract headers: IncomingHttpHeaders
constructor(public method: string, public url: string, public body: Body) {}
abstract parseBody(limit: string | number): Promise<any>
// Utils implemented using the abstract methods above
public get cookies() {
if (this._cookies) return this._cookies
return (this._cookies = getCookieParser(this.headers)())
}
}
export class NodeNextRequest extends BaseNextRequest<Readable> {
public headers = this.req.headers
set [NEXT_REQUEST_META](value: RequestMeta) {
// Mirror meta object to Node request for when `getRequestMeta` gets called on it
// This still happens in render.tsx
this.req[NEXT_REQUEST_META] = value
}
constructor(
public req: IncomingMessage & { [NEXT_REQUEST_META]?: RequestMeta }
) {
super(req.method!.toUpperCase(), req.url!, req)
}
async parseBody(limit: string | number): Promise<any> {
return parseBody(this.req, limit)
}
}
export class WebNextRequest extends BaseNextRequest<ReadableStream | null> {
public request: Request
public headers: IncomingHttpHeaders
constructor(request: Request) {
const url = new URL(request.url)
super(
request.method,
url.href.slice(url.origin.length),
request.clone().body
)
this.request = request
this.headers = {}
for (const [name, value] of request.headers.entries()) {
this.headers[name] = value
}
}
async parseBody(_limit: string | number): Promise<any> {
// TODO: implement parseBody for web
return
}
}
export abstract class BaseNextResponse<Destination = any> {
abstract statusCode: number | undefined
abstract statusMessage: string | undefined
abstract get sent(): boolean
constructor(public destination: Destination) {}
/**
* Sets a value for the header overwriting existing values
*/
abstract setHeader(name: string, value: string | string[]): this
/**
* Appends value for the given header name
*/
abstract appendHeader(name: string, value: string): this
/**
* Get all vaues for a header as an array or undefined if no value is present
*/
abstract getHeaderValues(name: string): string[] | undefined
abstract hasHeader(name: string): boolean
/**
* Get vaues for a header concatenated using `,` or undefined if no value is present
*/
abstract getHeader(name: string): string | undefined
abstract body(value: string): this
abstract send(): void
// Utils implemented using the abstract methods above
redirect(destination: string, statusCode: number) {
this.setHeader('Location', destination)
this.statusCode = statusCode
if (statusCode === PERMANENT_REDIRECT_STATUS) {
this.setHeader('Refresh', `0;url=${destination}`)
}
return this
}
}
export class NodeNextResponse extends BaseNextResponse<Writable> {
private textBody: string | undefined = undefined
constructor(public res: ServerResponse) {
super(res)
}
get sent() {
return this.res.finished || this.res.headersSent
}
get statusCode() {
return this.res.statusCode
}
set statusCode(value: number) {
this.res.statusCode = value
}
get statusMessage() {
return this.res.statusMessage
}
set statusMessage(value: string) {
this.res.statusMessage = value
}
setHeader(name: string, value: string | string[]): this {
this.res.setHeader(name, value)
return this
}
getHeaderValues(name: string): string[] | undefined {
const values = this.res.getHeader(name)
if (values === undefined) return undefined
return (Array.isArray(values) ? values : [values]).map((value) =>
value.toString()
)
}
hasHeader(name: string): boolean {
return this.res.hasHeader(name)
}
getHeader(name: string): string | undefined {
const values = this.getHeaderValues(name)
return Array.isArray(values) ? values.join(',') : undefined
}
appendHeader(name: string, value: string): this {
const currentValues = this.getHeaderValues(name) ?? []
if (!currentValues.includes(value)) {
this.res.setHeader(name, [...currentValues, value])
}
return this
}
body(value: string) {
this.textBody = value
return this
}
send() {
this.res.end(this.textBody)
}
}
export class WebNextResponse extends BaseNextResponse<WritableStream> {
private headers = new Headers()
private textBody: string | undefined = undefined
private _sent = false
private sendPromise = new Promise<void>((resolve) => {
this.sendResolve = resolve
})
private sendResolve?: () => void
private response = this.sendPromise.then(() => {
return new Response(this.textBody ?? this.transformStream.readable, {
headers: this.headers,
status: this.statusCode,
statusText: this.statusMessage,
})
})
public statusCode: number | undefined
public statusMessage: string | undefined
get sent() {
return this._sent
}
constructor(public transformStream = new TransformStream()) {
super(transformStream.writable)
}
setHeader(name: string, value: string | string[]): this {
this.headers.delete(name)
for (const val of Array.isArray(value) ? value : [value]) {
this.headers.append(name, val)
}
return this
}
getHeaderValues(name: string): string[] | undefined {
// https://developer.mozilla.org/en-US/docs/Web/API/Headers/get#example
return this.getHeader(name)
?.split(',')
.map((v) => v.trimStart())
}
getHeader(name: string): string | undefined {
return this.headers.get(name) ?? undefined
}
hasHeader(name: string): boolean {
return this.headers.has(name)
}
appendHeader(name: string, value: string): this {
this.headers.append(name, value)
return this
}
body(value: string) {
this.textBody = value
return this
}
send() {
this.sendResolve?.()
this._sent = true
}
toResponse() {
return this.response
}
}