This repository has been archived by the owner on Oct 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.js
69 lines (50 loc) · 1.76 KB
/
service.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
/*
* Backend REST services on Express
*/
const express = require("express");
const router = express.Router();
// MongoDB
const { MongoClient } = require("mongodb");
const client = new MongoClient("mongodb://root:[email protected]:27017?authMechanism=DEFAULT");
// GET products list
router.get("/products", async function (req, res) {
try {
await client.connect();
const database = client.db("mydb");
const products = database.collection("products");
// query products
const result = await products.find().toArray();
console.log(`/api/products returned ${result.length} product data`);
res.status(200).json(result);
} catch (err) {
console.log(err);
res.status(500).json({ "error": err });
} finally {
await client.close();
}
});
// POST order
router.post("/orders", async function (req, res) {
try {
let newId = 1;
await client.connect();
const database = client.db("mydb");
const orders = database.collection("orders");
// find the highest order id
if (await orders.countDocuments() > 0) {
const result = await orders.find().sort({ id: -1 }).limit(1).toArray();
newId = result[0].id + 1;
}
// write new order data
const newOrder = { ...req.body, id: newId };
await orders.insertOne(newOrder);
console.log(`/api/orders wrote new order: ${JSON.stringify(newOrder)}`);
res.status(200).json({ "id": newId });
} catch (err) {
console.log(err);
res.status(500).json({ "error": err });
} finally {
await client.close();
}
});
module.exports = router