-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
51 lines (51 loc) · 1.62 KB
/
app.js
File metadata and controls
51 lines (51 loc) · 1.62 KB
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
const http = require("http");
const url = require("url");
const fs = require("fs");
const cors = require("cors");
const path = require("path");
const {
getProducts,
getProduct,
createProduct,
updateProduct,
deleteProduct,
} = require("./controllers/product_contorler");
const server = http.createServer((req, res, id) => {
cors()(req, res, () => {
if (req.url === "/api/product/" && req.method === "GET") {
getProducts(req, res);
} else if (
req.url.match(/\/api\/product\/[a-zA-Z0-9-]+$/) &&
req.method === "GET"
) {
const id = req.url.split("/")[3];
getProduct(req, res, id);
} else if (req.url === "/api/product/" && req.method === "POST") {
const id = req.url.split("/")[3];
createProduct(req, res, id);
} else if (
req.url.match(/\/api\/product\/([0-9]+)/) &&
req.method === "PUT"
) {
const id = req.url.split("/")[3];
updateProduct(req, res, id);
} else if (
req.url.match(/\/api\/product\/[a-zA-Z0-9-]+$/) &&
req.method === "DELETE"
) {
const id = req.url.split("/")[3];
deleteProduct(req, res, id);
} else {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.writeHead(404, { "Content-type": "application/json" });
res.end(JSON.stringify({ message: "not found" }));
}
});
});
const PORT = process.env.PORT || 2000;
server.listen(PORT, () => console.log(`Server running at ${PORT}`));