-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
75 lines (68 loc) · 2.04 KB
/
app.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
'use strict';
const Koa = require('koa');
const path = require('path');
const cors = require('kcors');
const Pug = require('koa-pug');
const views = require('koa-views');
const serve = require('koa-static');
const koaBody = require('koa-body');
const logger = require('koa-logger');
const router = require('koa-router')();
const app = new Koa();
app
// Enable ALL CORS Requests
.use(cors({
origin: '*',
maxAge: 24 * 60 * 60,
methods: [ 'GET', 'PUT', 'DELETE', 'POST', 'PATCH', 'OPTIONS' ],
allowedHeaders: [ 'Content-Type', 'Yellgar-Token', 'Yellgar-User-Id' ]
}))
.use(logger())
.use(koaBody())
.use(views(__dirname, { extension: 'pug' }))
.use(serve(path.join(__dirname, 'public')))
.use(router.routes())
.use(router.allowedMethods({ throw: true }))
.use(async (ctx, next) => {
ctx.request.setTimeout(10000);
await next;
});
const pug = new Pug({
viewPath: './views',
debug: process.env.NODE_ENV === 'development'
});
pug.use(app);
const crawler = require('./crawler.js');
crawler(router);
app.on('error', (err, ctx) => {
try {
const statusCode = ctx.status || 500;
if (statusCode === 500) {
console.error(err.stack || err);
}
ctx.response.status = statusCode;
// 預設不輸出異常詳情
let error = {};
ctx.response.body = {
extra: error,
status: ctx.response.status,
level: 'error',
message: 'unexpected error'
};
} catch (error) {
console.error('Error handle fail :', error);
}
});
const PORT = process.env.PORT || 3000;
const server = app.listen(PORT, () => {
console.info('===========================================');
console.info(`===== Server is running at port: ${PORT} =====`);
console.info('===========================================');
// 註冊全域未捕獲異常的處理器
process.on('uncaughtException', (err) => {
console.error('Caught exception: ', err.stack);
});
process.on('unhandledRejection', (reason, p) => {
console.error('Unhandled Rejection at: Promise ', p, ' reason: ', reason.stack);
});
});