-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
73 lines (59 loc) · 1.98 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 bodyParser = require('body-parser');
const cors = require('cors');
const db = require('./configs/database');
process.env.NODE_ENV = process.env.NODE_ENV ?? 'development';
let authMiddleware = require('./middlewares/auth');
const authRouter = require('./routes/auth');
const usersRouter = require('./routes/users');
const postsRouter = require('./routes/posts');
db.authenticate().then(() => {
console.log('Database connected...');
// Create database tables if not exists
// (async () => await db.sync())();
}).catch(err => {
console.log('Error: ' + err);
process.exit();
});
const port = process.env.PORT || 3000;
const app = express();
// Prevent public stack traces on production
process.env.NODE_ENV === 'production' ? app.set('env', 'production') : app.set('env', 'development');
// Mddlewares
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// app.use(express.urlencoded({ extended: true }));
// app.use(express.json());
app.use(cors({
origin: '*'
}));
app.use((err, req, res, next) => {
if (err instanceof SyntaxError && err.status === 400 && "body" in err) {
res.status(400).send({
message: 'Malformed request body has been sent!'
});
} else next();
});
// Default routes
app.get('/', (req, res) => {
res.json({"message": "Welcome to CMS API"});
});
// Auth route
app.use('/auth', authRouter);
// Auth middlewares
// app.use(authMiddleware);
// Bypass auth middlewares (debug)
process.env.NODE_ENV === 'debug' ? authMiddleware = (req, res, next) => { next() } : console.log({ NODE_ENV: process.env.NODE_ENV });
// App routes
app.use('/users', authMiddleware, usersRouter);
app.use('/posts', authMiddleware, postsRouter);
// Invalid routes
app.use('/*', (req, res)=>{
return res.status(404).json({
error : true,
message : '404 Not found!'
})
});
app.listen(port, () => {
console.log(`CMS server is listening on port ${port}`);
});