forked from vercel/micro
/
index.js
171 lines (138 loc) · 4.12 KB
/
index.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
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
// Native
const server = require('http').Server;
const {Stream} = require('stream');
// Packages
const contentType = require('content-type');
const getRawBody = require('raw-body');
// based on is-stream https://github.com/sindresorhus/is-stream/blob/c918e3795ea2451b5265f331a00fb6a8aaa27816/license
function isStream(stream) {
return stream !== null &&
typeof stream === 'object' &&
typeof stream.pipe === 'function';
}
function readable(stream) {
return isStream(stream) &&
stream.readable !== false &&
typeof stream._read === 'function' &&
typeof stream._readableState === 'object';
}
const {NODE_ENV} = process.env;
const DEV = NODE_ENV === 'development';
const serve = fn => server((req, res) => exports.run(req, res, fn));
module.exports = serve;
exports = serve;
exports.default = serve;
const createError = (code, message, original) => {
const err = new Error(message);
err.statusCode = code;
err.originalError = original;
return err;
};
const send = (res, code, obj = null) => {
res.statusCode = code;
if (obj === null) {
res.end();
return;
}
if (Buffer.isBuffer(obj)) {
if (!res.getHeader('Content-Type')) {
res.setHeader('Content-Type', 'application/octet-stream');
}
res.setHeader('Content-Length', obj.length);
res.end(obj);
return;
}
if (obj instanceof Stream || readable(obj)) {
if (!res.getHeader('Content-Type')) {
res.setHeader('Content-Type', 'application/octet-stream');
}
obj.pipe(res);
return;
}
let str = obj;
if (typeof obj === 'object' || typeof obj === 'number') {
// We stringify before setting the header
// in case `JSON.stringify` throws and a
// 500 has to be sent instead
// the `JSON.stringify` call is split into
// two cases as `JSON.stringify` is optimized
// in V8 if called with only one argument
if (DEV) {
str = JSON.stringify(obj, null, 2);
} else {
str = JSON.stringify(obj);
}
if (!res.getHeader('Content-Type')) {
res.setHeader('Content-Type', 'application/json; charset=utf-8');
}
}
res.setHeader('Content-Length', Buffer.byteLength(str));
res.end(str);
};
const sendError = (req, res, errorObj) => {
const statusCode = errorObj.statusCode || errorObj.status;
const message = statusCode ? errorObj.message : 'Internal Server Error';
send(res, statusCode || 500, DEV ? errorObj.stack : message);
if (errorObj instanceof Error) {
console.error(errorObj.stack);
} else {
console.warn('thrown error must be an instance Error');
}
};
exports.send = send;
exports.sendError = sendError;
exports.createError = createError;
exports.run = (req, res, fn) =>
new Promise(resolve => resolve(fn(req, res)))
.then(val => {
if (val === null) {
send(res, 204, null);
return;
}
// Send value if it is not undefined, otherwise assume res.end
// will be called later
// eslint-disable-next-line no-undefined
if (val !== undefined) {
send(res, res.statusCode || 200, val);
}
})
.catch(err => sendError(req, res, err));
// Maps requests to buffered raw bodies so that
// multiple calls to `json` work as expected
const rawBodyMap = new WeakMap();
const parseJSON = str => {
try {
return JSON.parse(str);
} catch (err) {
throw createError(400, 'Invalid JSON', err);
}
};
exports.buffer = (req, {limit = '1mb', encoding} = {}) =>
Promise.resolve().then(() => {
const type = req.headers['content-type'] || 'text/plain';
const length = req.headers['content-length'];
// eslint-disable-next-line no-undefined
if (encoding === undefined) {
encoding = contentType.parse(type).parameters.charset;
}
const body = rawBodyMap.get(req);
if (body) {
return body;
}
return getRawBody(req, {limit, length, encoding})
.then(buf => {
rawBodyMap.set(req, buf);
return buf;
})
.catch(err => {
if (err.type === 'entity.too.large') {
throw createError(413, `Body exceeded ${limit} limit`, err);
} else {
throw createError(400, 'Invalid body', err);
}
});
});
exports.text = (req, {limit, encoding} = {}) =>
exports.buffer(req, {limit, encoding}).then(body => body.toString(encoding));
exports.json = (req, opts) =>
exports.text(req, opts).then(body => parseJSON(body));