-
Notifications
You must be signed in to change notification settings - Fork 2
/
reply.js
114 lines (94 loc) · 2.41 KB
/
reply.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
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
// https://www.fastify.io/docs/latest/Reference/Reply
// - statusCode ✅
// - code(statusCode) ✅
// - header(key, value) ✅
// - headers(object) ✅
// - getHeader(key) ✅
// - getHeaders() ✅
// - removeHeader(key) ✅
// - hasHeader(key) ✅
// - trailer(key, function) ❌
// - hasTrailer(key) ❌
// - removeTrailer(key) ❌
// - redirect([code,] dest) ✅
// - callNotFound() ❌
// - getResponseTime() ❌
// - type(contentType) ✅
// - serializer(func) ❌
// - sent ❌
// - hijack() ❌
// - type (contentType) ✅
// - send (data) ✅
const kStatusCode = Symbol('kStatusCode');
const kHeaders = Symbol('kHeaders');
const kRequest = Symbol('kRequest');
const buildRedirectLocation = Symbol('buildRedirectLocation');
export const kRedirect = Symbol('kRedirect');
export const kBody = Symbol('kBody');
export const kResponse = Symbol('kResponse');
export default class FastifyEdgeReply {
[kStatusCode] = 200
get [kResponse] () {
return {
status: this[kStatusCode],
headers: this[kHeaders],
};
}
constructor (req) {
this[kRequest] = req;
this[kHeaders] = {};
}
get statusCode () {
return this[kStatusCode];
}
set statusCode (statusCode) {
this[kStatusCode] = statusCode;
}
code (statusCode) {
this[kStatusCode] = statusCode;
}
header (key, value) {
this[kHeaders][key] = value;
}
headers (object) {
Object.assign(this[kHeaders], object);
}
getHeader (key) {
return this[kHeaders][key];
}
getHeaders () {
return this[kHeaders];
}
removeHeader (key) {
delete this[kHeaders][key];
}
hasHeader (key) {
return key in this[kHeaders];
}
redirect (...args) {
if (args.length === 1) {
this[kRedirect] = [this[buildRedirectLocation](args[0]), 302];
} else {
this[kRedirect] = [this[buildRedirectLocation](args[1]), args[0]];
}
}
type (contentType) {
this[kHeaders]['content-type'] = contentType;
}
send (data) {
if (typeof data === 'string') {
if (!('content-type' in this[kHeaders])) {
this[kHeaders]['content-type'] = 'text/plain; charset=utf-8';
}
this[kBody] = data;
} else if (typeof data === 'object') {
this[kBody] = JSON.stringify(data, null, 2);
}
}
[buildRedirectLocation] (location) {
if (!location.startsWith('http')) {
return `${this[kRequest].protocol}://${this[kRequest].origin}${location}`;
}
return location;
}
}