forked from oakserver/oak
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.ts
187 lines (167 loc) · 5.84 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
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
// Copyright 2018-2019 the oak authors. All rights reserved. MIT license.
import { ServerRequest } from "./deps.ts";
import { preferredEncodings } from "./encoding.ts";
import httpErrors from "./httpError.ts";
import { isMediaType } from "./isMediaType.ts";
import { preferredMediaTypes } from "./mediaType.ts";
import { HTTPMethods } from "./types.ts";
export enum BodyType {
JSON = "json",
Form = "form",
Text = "text",
Undefined = "undefined"
}
export type Body =
| { type: BodyType.JSON; value: any }
| { type: BodyType.Form; value: URLSearchParams }
| { type: BodyType.Text; value: string }
| { type: BodyType.Undefined; value: undefined };
const decoder = new TextDecoder();
const jsonTypes = ["json", "application/*+json", "application/csp-report"];
const formTypes = ["urlencoded"];
const textTypes = ["text"];
export class Request {
private _body?: Body;
private _path: string;
private _rawBodyPromise?: Promise<Uint8Array>;
private _search?: string;
private _searchParams: URLSearchParams;
private _serverRequest: ServerRequest;
/** Is `true` if the request has a body, otherwise `false`. */
get hasBody(): boolean {
return (
this.headers.get("transfer-encoding") !== null ||
!!parseInt(this.headers.get("content-length") || "")
);
}
/** The `Headers` supplied in the request. */
get headers(): Headers {
return this._serverRequest.headers;
}
/** The HTTP Method used by the request. */
get method(): HTTPMethods {
return this._serverRequest.method as HTTPMethods;
}
/** The path of the request. */
get path(): string {
return this._path;
}
/** The search part of the URL of the request. */
get search(): string | undefined {
return this._search;
}
/** The parsed `URLSearchParams` of the request. */
get searchParams(): URLSearchParams {
return this._searchParams;
}
/** Returns the _original_ Deno server request. */
get serverRequest(): ServerRequest {
return this._serverRequest;
}
/** The URL of the request. */
get url(): string {
return this._serverRequest.url;
}
constructor(serverRequest: ServerRequest) {
this._serverRequest = serverRequest;
const [path, search] = serverRequest.url.split("?");
this._path = path;
this._search = search ? `?${search}` : undefined;
this._searchParams = new URLSearchParams(search);
}
/** Returns an array of media types, accepted by the requestor, in order of
* preference. If there are no encodings supplied by the requestor,
* `undefined` is returned.
*/
accepts(): string[];
/** For a given set of media types, return the best match accepted by the
* requestor. If there are no encoding that match, then the method returns
* `undefined`.
*/
accepts(...types: string[]): string | undefined;
accepts(...types: string[]): string | string[] | undefined {
const acceptValue = this._serverRequest.headers.get("Accept");
if (!acceptValue) {
return;
}
if (types.length) {
return preferredMediaTypes(acceptValue, types)[0];
}
return preferredMediaTypes(acceptValue);
}
acceptsCharsets(): string[];
acceptsCharsets(...charsets: string[]): string | undefined;
acceptsCharsets(...charsets: string[]): string[] | string | undefined {
return undefined;
}
/** Returns an array of encodings, accepted the the requestor, in order of
* preference. If there are no encodings supplied by the requestor,
* `undefined` is returned.
*/
acceptsEncodings(): string[];
/** For a given set of encodings, return the best match accepted by the
* requestor. If there are no encodings that match, then the method returns
* `undefined`.
*
* **NOTE:** You should always supply `identity` as one of the encodings
* to ensure that there is a match when the `Accept-Encoding` header is part
* of the request.
*/
acceptsEncodings(...encodings: string[]): string | undefined;
acceptsEncodings(...encodings: string[]): string[] | string | undefined {
const acceptEncodingValue = this._serverRequest.headers.get(
"Accept-Encoding"
);
if (!acceptEncodingValue) {
return;
}
if (encodings.length) {
return preferredEncodings(acceptEncodingValue, encodings)[0];
}
return preferredEncodings(acceptEncodingValue);
}
acceptsLanguages(): string[];
acceptsLanguages(...langs: string[]): string | undefined;
acceptsLanguages(...langs: string[]): string[] | string | undefined {
return undefined;
}
/** If there is a body in the request, resolves with an object which
* describes the body. The `type` provides what type the body is and `body`
* provides the actual body.
*/
async body(): Promise<Body> {
if (this._body) {
return this._body;
}
const encoding = this.headers.get("content-encoding") || "identity";
if (encoding !== "identity") {
throw new httpErrors.UnsupportedMediaType(
`Unsupported content-encoding: ${encoding}`
);
}
if (!this.hasBody) {
return { type: BodyType.Undefined, value: undefined };
}
const contentType = this.headers.get("content-type");
if (contentType) {
const rawBody = await (this._rawBodyPromise ||
(this._rawBodyPromise = this._serverRequest.body()));
const str = decoder.decode(rawBody);
if (isMediaType(contentType, jsonTypes)) {
return (this._body = { type: BodyType.JSON, value: JSON.parse(str) });
} else if (isMediaType(contentType, formTypes)) {
return (this._body = {
type: BodyType.Form,
value: new URLSearchParams(str)
});
} else if (isMediaType(contentType, textTypes)) {
return (this._body = { type: BodyType.Text, value: str });
}
}
throw new httpErrors.UnsupportedMediaType(
contentType
? `Unsupported content-type: ${contentType}`
: "Missing content-type"
);
}
}