-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
125 lines (111 loc) · 3.23 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
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
const express = require("express");
const mysql = require("mysql2/promise");
const { createServer } = require("http");
const { validationResult, checkSchema } = require("express-validator");
const bodyParser = require("body-parser");
const cors = require("cors");
// ENV CONFIGURATION
require("dotenv").config();
// CORE APP CONFIGURATION
const app = express();
const httpServer = createServer(app);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(
cors({
origin: process.env.ORIGIN_URL,
})
);
const pool = mysql.createPool(process.env.DATABASE_URL);
/* TABLE STRUCTURE
id - auto incremented int.
name - string 64size
price - float 24
*/
const schema = {
name: {
in: ["body"],
errorMessage: "The name you entered is not valid.",
escape: true,
trim: true,
custom: {
options: (value) => value.match(/^[A-Za-z \d]+$/),
},
},
price: {
in: ["body"],
errorMessage: "The price you entered is not valid.",
isNumeric: true,
toFloat: true,
},
// key_auth: {
// in: ["headers"],
// errorMessage: "Invalid authorization key.",
// custom: {
// options: (value) => value == process.env.SECRET_AUTH,
// },
// },
};
// Retrieve all products
app.get("/api/products/", (req, res) => {
pool.execute("SELECT * FROM `products`;")
.then(([rows]) => res.status(200).send(rows))
.catch(() =>
res.status(202).json({
msg: "An error occured while trying to fetch products.",
status: 202,
})
);
});
// Retrieve specific product
app.get("/api/products/:name", (req, res) => {
const name = req.params.name;
pool.execute(
"SELECT * FROM `products` WHERE `name` like CONCAT( '%', ?, '%');",
[name]
)
.then(([rows]) => res.status(200).json(rows))
.catch(() =>
res.status(202).json({
msg: "An error occured while trying to fetch products.",
status: 202,
})
);
});
// Add Product
app.post("/api/products/", checkSchema(schema), (req, res) => {
const result = validationResult(req);
if (!result.isEmpty()) {
return res.status(202).json({
msg: result.errors[0].msg,
status: 202,
});
}
const name = req.body.name;
const price = req.body.price;
pool.execute("INSERT INTO `products` (name, price) VALUES (?, ?);", [
name,
price,
])
.then(() =>
res.status(200).json({
msg: "Product added successfully.",
status: 200,
})
)
.catch((err) => {
if (err.code == "ER_DUP_ENTRY") {
res.status(202).json({
msg: "A product already exists with that name.",
status: 202,
});
} else {
res.status(202).json({
msg: "An error occured while trying to add a new product.",
status: 202,
});
}
});
});
httpServer.listen(process.env.PORT, () => {
console.log("Application is served at port: " + process.env.PORT);
});