-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
100 lines (87 loc) · 2.68 KB
/
server.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
const express = require('express');
const mongodb = require('mongodb');
require('dotenv').config();
const cors = require('cors');
const MongoClient = require('mongodb').MongoClient;
const app = express();
const logger = require('./middleware/logger');
var db;
const port = process.env.PORT;
const mongo_url = process.env.MONGO_URI;
app.use(express.json())
app.use(cors());
app.use(express.static('img'))
app.get('/lessons', logger, function (req, res) {
db.collection('lessons').find({}).toArray(function(err, result) {
res.setHeader('Access-Control-Allow-Origin', "*")
res.json(result)
})
});
app.post('/orders', function (req, res) {
console.log(req.body)
db.collection('order_info').insertOne(req.body, function (
err,
result
) {
res.setHeader('Access-Control-Allow-Origin', "*")
res.json(result)
})
});;
function createOrder(order){
db.collection('order_info').insertOne(order, function (
err,
result
) {
console.log(result)
})
}
app.put('/buy-lessons',logger, function (req, res) {
// return res.json(req.body.user)
req.body.cart.forEach(data => {
db.collection('lessons').findOne({_id : new mongodb.ObjectId(data._id)})
.then(obj => {
if (obj.spaces == 0) {
db.collection('lessons').findOne({_id : new mongodb.ObjectId(data._id)})
.then(obj => {
res.json(obj)
})
}else{
let updatedData = { $set: {space : obj.spaces-data.reserved} }
db.collection('lessons').findOneAndUpdate({_id : new mongodb.ObjectId(data._id)}, updatedData)
.then(obj => {
let order = {
courseName: data.name,
full_name: req.body.user.full_name,
phone: req.body.user.phone,
quantity: data.reserved
}
createOrder(order);
res.json(obj)
})
}
})
});
});
app.get('/search-lessons', logger, function (req, res) {
console.log(req.query.keyword)
db.collection('lessons').find({"$or":[
{'name': {'$regex': req.query.keyword, '$options' : 'i'}},
{'location': {'$regex': req.query.keyword, '$options' : 'i'}}
]}).toArray(function(err, result) {
res.setHeader('Access-Control-Allow-Origin', "*")
res.json(result)
})
});
app.use((req, res) => {
res.send({
"error": "Bad Request"
})
})
app.listen(port, () => {
console.log(`server listening on port: ${port}`);
MongoClient.connect(mongo_url, (err, client) => {
if (err) throw err;
console.log('database connected!!');
db = client.db('School_work')
})
})