-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
32 lines (29 loc) · 898 Bytes
/
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
const {send, sendError, json} = require('micro');
const globalRouter = require('./router');
module.exports = exports = serve;
exports.__defineGetter__('router', () => globalRouter);
async function serve(req, res) {
const handler = globalRouter.match(req, res, { json });
if (!handler) {
// we want error with json body
res.setHeader('content-type', 'application/json');
const err = new Error('Not Found');
err.message = JSON.stringify({ message: 'Not Found' });
err.statusCode = 404;
return sendError(req, res, err);
}
try {
return await handler();
} catch (err) {
if (typeof err.message === 'string') {
try {
const obj = JSON.parse(err.message);
if (typeof obj === 'object') {
res.setHeader('content-type', 'application/json');
}
} catch (exception) {
sendError(req, res, err);
}
}
}
}