-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
130 lines (109 loc) · 3.23 KB
/
server.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
const fs = require('fs')
const path = require('path');
const express = require('express');
const dotenv = require('dotenv');
// const logger = require('./middlewares/logger');
const fileupload = require('express-fileupload');
const cookieParser = require('cookie-parser');
const helmet = require('helmet');
const xss = require('xss-clean');
const rateLimit = require('express-rate-limit');
const hpp = require('hpp');
const cors = require('cors');
const errorHandler = require('./middlewares/error');
const morgan = require('morgan');
const swaggerJsdoc = require("swagger-jsdoc");
const swaggerUi = require("swagger-ui-express");
const app = express();
// Body parser
app.use(express.json());
// Cookie parser
app.use(cookieParser());
// Routes file
const files = require('./routes/files');
// Load env vars
dotenv.config({ path: './config/.env' });
// Custom Middleware
// app.use(logger);
// Create Logger file
// app.use(morgan('dev'));
let today = new Date();
let fileName = process.env.NODE_ENV + '-' + today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate() + '.log';
let logDir = path.join(__dirname, 'logs');
// Create the directory if it doesn't exist
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir, { recursive: true });
}
// Create the write stream
let accessLogStream = fs.createWriteStream(path.join(logDir, fileName), { flags: 'a' });
app.use(morgan('combined', { stream: accessLogStream }))
// File uploading
app.use(fileupload());
// Set security headers
app.use(helmet());
// Prevent xss attacks
app.use(xss());
// Rate limiting
const limiter = rateLimit({
windowMs: 10 * 60 * 1000, // 10 minutes
max: 100
});
app.use(limiter);
// Prevent http param pollution
app.use(hpp());
// Enable CORS
app.use(cors());
// Swagger config
const swaggerDefinition = {
openapi: "3.0.0",
info: {
title: "API File Storage",
version: "0.0.1",
description:
"This is a simple API for uploading and getting files.",
license: {
name: "MIT",
url: "https://spdx.org/licenses/MIT.html",
},
contact: {
name: "Ramdani",
url: "https://github.com/ramdani15",
email: "[email protected]",
},
},
components: {
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
}
}
},
security: [{
bearerAuth: []
}]
};
const swaggerOptions = {
swaggerDefinition,
apis: ["./routes/*.js"],
};
const swaggerSpecs = swaggerJsdoc(swaggerOptions);
// Set static folder
app.use(express.static(path.join(__dirname, 'public')));
// Mount routers
// TODO: refactor routes versioning
app.use('/api/v1/files', files);
app.use("/api/v1/swagger", swaggerUi.serve, swaggerUi.setup(swaggerSpecs));
app.use(errorHandler);
const PORT = process.env.PORT || 3000;
const server = app.listen(
PORT,
console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`)
);
// Handle unhandled promise rejections
process.on('unhandledRejection', (err, promise) => {
console.log(`Error : ${err.message}`);
// Close server & exit process
server.close(() => process.exit(1));
})