-
Notifications
You must be signed in to change notification settings - Fork 2
/
request.js
73 lines (67 loc) · 1.64 KB
/
request.js
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
// query
// body
// params
// headers
// raw
// req
// server
// id
// log
// ip
// ips
// hostname
// protocol
// method
// url
// routerMethod
// routerPath
// is404
// connection
// socket
// context
const kBody = Symbol('kBody');
export const readBody = Symbol('readBody');
export default class FastifyEdgeRequest {
url = null
query = null
body = null
params = null
headers = null
raw = null
constructor (request, url, route) {
this.url = `${url.pathname}${url.search}`;
this.origin = url.origin;
this.hostname = url.hostname;
this.protocol = url.protocol.replace(':', '');
this.raw = request;
this.query = new Proxy(url.searchParams, {
get: (params, param) => params.get(param),
});
this.params = route.params;
this.headers = new Proxy(this.raw.headers, {
get: (headers, header) => headers.get(header),
});
}
get body () {
return this[kBody] || this.raw.body;
}
async [readBody] () {
// Mostly adapted from https://developers.cloudflare.com/workers/examples/read-post/
const { headers } = this.raw;
const contentType = headers.get('content-type') || '';
if (contentType.includes('application/json')) {
this[kBody] = await this.raw.json();
} else if (contentType.includes('application/text')) {
this[kBody] = this.raw.text();
} else if (contentType.includes('text/html')) {
this[kBody] = this.raw.text();
} else if (contentType.includes('form')) {
const formData = await this.raw.formData();
const body = {};
for (const entry of formData.entries()) {
body[entry[0]] = entry[1];
}
this[kBody] = body;
}
}
}