-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
230 lines (216 loc) · 7.88 KB
/
server.js
File metadata and controls
230 lines (216 loc) · 7.88 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
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
const express = require('express')
const next = require('next')
var https = require('https');
var http = require('http');
const bodyParser = require('body-parser');
// MongoDB schema models
const Component = require('./models/Component');
const Transaction = require('./models/Transaction');
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler();
// import CORS and fs for file reading
const cors = require('cors');
var fs = require('fs');
const cheerio = require('cheerio');
const fetch = require('node-fetch');
const server = express();
const HTTPS = true;
const serverRun = HTTPS
? https.createServer({
key: fs.readFileSync('./certificates/localhost.key'),
cert: fs.readFileSync('./certificates/localhost.crt'),
}, server)
: http.createServer({}, server);
// Link db connection
require('./config/db');
app.prepare().then(() => {
server.use(cors());
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));
server.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
);
next();
});
// GET routes
server.get('/api/get', async (req, res) => {
// Retrieve query keys
const componentName = req.query.name;
const componentLocation = req.query.location;
const componentPartID = req.query.part_id;
const componentRetailID = req.query.retail_id;
// When user search for component name
if (componentName) {
// Compare input component name with Component Collection
console.log("Query with component name: " + componentName);
// Query the database
await Component.find({ component_name: { $regex: componentName.toString(), $options: "i" } }, async function (err, result) {
if (err) throw err;
res.json(result);
})
}
else if (componentLocation) {
// Compare input componentID with Component Collection
console.log("Query with component id: " + componentID);
// Query the database
await Component.find({ "location": componentLocation }, async function (err, result) {
if (err) throw err;
res.json(result);
})
} else if (componentPartID) {
// Compare input component part number with Component Collection
console.log("Query with component part number: " + componentPartID);
// Query the database
await Component.find({ "part_number": { $regex: componentPartID.toString(), $options: "i" } }, async function (err, result) {
if (err) throw err;
res.json(result);
})
} else if (componentRetailID) {
// Compare input component retail number with Component Collection
console.log("Query with component retail part number: " + componentRetailID);
// Query the database
await Component.find({ "retail_part_number": { $regex: componentRetailID.toString(), $options: "i" } }, async function (err, result) {
if (err) throw err;
res.json(result);
})
} else {
res.sendStatus(400);
}
})
// HELPER FUNCTION FOR POST ROUTES
async function checkQuantity(input, cb) {
var validated_orders = [];
// Update quantity in component collection
input.forEach(async function (item, index, arr) {
// Check order if all quanity is valid
await Component.find({ "component_id": item.component_id }, async function (err, result) {
if (err) throw err;
validated_orders.push(
{
component_id: item.component_id,
quantity: item.deposit ? result[0].quantity + item.quantity : result[0].quantity - item.quantity
}
);
})
if (index === arr.length - 1) {
// callbacks the value
cb(validated_orders, "validated_orders");
}
});
}
// POST routes for new transaction
server.post('/api/update', async (req, res) => {
var validated_orders = [];
try {
// Create a promise and user checkQuanity function so that it would execute sequentially before create a new transaction in db
await new Promise((resolve, reject) => {
checkQuantity(req.body.order_details, (value, status) => {
if (status === 'validated_orders') {
validated_orders = value;
}
// Resolve when its done to execute the next line of codd
resolve();
});
});
// Exit or execute queries to database
if (validated_orders.map(item => item.quantity).some(e => e < 0)) {
// Send back 400
res.status(400).json({ error: 'Insufficient quantity for order!' });
} else {
// If order is valid, loop through each component to update the new quantity in db
validated_orders.forEach(async function (item) {
await Component.updateOne(
{ component_id: item.component_id },
{
$set:
{ quantity: item.quantity }
},
function (err, response) {
if (err) throw err;
console.log('Collection Component updated sucessfully!');
}
);
})
// Retrieve current time for transaction
const time = new Date();
const formattedTime =
time.getDate() + "-" +
(parseInt(time.getMonth()) + 1).toString() + "-" +
time.getFullYear() + " " +
time.getHours() + ":" +
time.getMinutes() + ":" +
time.getSeconds();
// Format the transaction details
const transaction = new Transaction
({
student_id: req.body.stu_id,
student_name: req.body.stu_name,
time: formattedTime,
order_details: req.body.order_details
});
// Save to Transaction collection in db
transaction.save(function (err) {
console.log("Timestamp: " + formattedTime + ". Transaction has been successfully made");
return res.sendStatus(200);
})
}
} catch (err) {
if (err) res.status(404).send({ error: 'Unsucessful POST request!' });
}
})
// POST routes for new component
server.post('/api/insert', async (req, res) => {
try {
// Check if component already exist
await Component.find({ "part_number": req.body.part_number }, async function (err, result) {
if (err) throw err;
if (result.length !== 0) {
// Send back 400
res.status(401).json({ error: 'Component already exist!' });
} else {
var content = req.body;
// Scrap component image from product website
await fetch(req.body.url)
.then(res => res.text())
.then(text => {
const $ = cheerio.load(text);
$(".product-photo-large").each((index, image) => {
var img = $(image).attr('href');
content.url = img;
})
})
// Filter component object
for (var key in content) {
if (content[key].toString() === "" && key.toString() !== "quantity") {
content[key] = "n/a";
} else if (key.toString() === "quantity") {
content[key] = 0;
}
}
// Insert new component
await Component.create(content);
console.log("New component has been created in the database!");
return res.sendStatus(200);
}
})
} catch (err) {
if (err) {
console.log(err);
res.status(404).send({ error: 'Insert new component unsucessful!' })
}
}
})
// Hanlde client routes
server.all('*', (req, res) => {
return handle(req, res)
})
serverRun.listen(port, (err) => {
if (err) throw err
console.log(`> Server ready on http${HTTPS ? 's' : ''}://localhost:${port}`);
})
})