-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
48 lines (40 loc) · 1.27 KB
/
index.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
const express = require("express");
const helmet = require("helmet");
const cors = require("cors");
const { contactsEndpointHandler } = require("./contacts");
const { adaptRequest } = require("./helpers/adapt-request");
const { config } = require("./config");
require("dotenv").config();
const PORT = config.port;
const app = express();
// middleware
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(cors({ origin: "http://localhost:3001" })); // TODO: set origin depending on process.env.NODE_ENV
app.use(helmet());
// routes
app.all("/contacts", contactsController);
app.get("/contacts/:id", contactsController);
app.delete("/contacts/:id", contactsController);
// controllers
/**
* Contacts Controller
* Keep business logic out of here
* @param {import("@types/express").Request} req
* @param {import("@types/express").Response} res
*/
function contactsController(req, res) {
const httpRequest = adaptRequest(req);
contactsEndpointHandler(httpRequest)
.then(({ headers, statusCode, data }) =>
res
.set(headers)
.status(statusCode)
.send(data)
)
.catch(error => {
console.log(error);
res.status(500).end();
});
}
app.listen(PORT, () => console.log(`Listening on http://localhost:${PORT}`));