forked from ispoljari/speck-academy-booking-app-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
64 lines (53 loc) · 1.52 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
require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const sessionRepository = require("./repositories/sessions");
const { DateTime } = require("luxon");
const cookieParser = require("cookie-parser");
const { PORT, CLIENT_ORIGIN, COOKIE_SECRET_KEY } = require("./config");
const { HTTP_STATUS_CODES } = require("./enums");
const {
hallsHandler,
reservationsHandler,
adminsHandler
} = require("./route-handlers");
const { notFound } = require("./enums/error-responses");
const app = express();
app.use(
cors({
origin: CLIENT_ORIGIN,
credentials: true
})
);
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: true
})
);
app.use(cookieParser(COOKIE_SECRET_KEY));
// Base routes
app.use(async (req, res, next) => {
try {
const { sessionId } = req.signedCookies;
const session = await sessionRepository.getById(sessionId);
const isAdmin =
Boolean(session) &&
DateTime.local() <= DateTime.fromJSDate(session.expiryDate);
req.isAdmin = isAdmin;
next();
} catch (error) {
next(error);
}
});
app.use("/api/halls", hallsHandler);
app.use("/api/reservations", reservationsHandler);
app.use("/api/admins", adminsHandler);
app.use((req, res, next) => next(notFound));
app.use((err, req, res, next) => {
res.status(err.status || HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR).send({
message: err.message
});
});
app.listen(PORT, () => console.log(`Server Listening on port ${PORT}!`));