-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
73 lines (60 loc) · 1.86 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
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const cors = require('cors');
const { generalLimiter } = require('./middlewares/rateLimiters.js');
const handleError = require('./service/handleError.js');
const swaggerUi = require('swagger-ui-express');
const swaggerDocs = require('./swagger.js');
// 記錄重大錯誤
process.on('uncaughtException', (err) => {
console.error('Uncaught Fatal Exception !\n', err);
process.exit(1);
});
// 未捕捉到的 catch
process.on('unhandledRejection', (reason, promise) => {
console.error('未捕捉到的 rejection:\n', promise);
console.error('原因:\n', reason);
});
// router
const postRouter = require('./routes/post');
const postsRouter = require('./routes/posts');
const userRouter = require('./routes/user');
const uploadRouter = require('./routes/upload');
const app = express();
// 連接資料庫
require('./connections/mongodb.js');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());
app.use(generalLimiter);
// router
app.use('/post', postRouter);
app.use('/posts', postsRouter);
app.use('/user', userRouter);
app.use('/upload', uploadRouter);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));
// catch 404
app.use((req, res, next) => {
res.status(404).send({
success: false,
message: 'API 路徑不存在',
});
});
// error handler
app.use((err, req, res, next) => {
handleError(err);
const response = {
success: false,
message: err.message || '發生錯誤,請聯絡管理員',
};
if (process.env.NODE_ENV === 'dev') {
response.error = err;
}
res.status(err.statusCode || 500).send(response);
});
module.exports = app;