-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
253 lines (225 loc) · 8.16 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
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
var fs = require('fs');
var express = require('express');
var cors = require('cors');
var mime = require('mime');
var stream = require('stream');
var path = require('path');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true,
limit: '50mb'
}));
app.use(bodyParser.json({limit: '50mb', extended: true}));
//app.use(express.json());
var port = process.env.PORT || 8090;
var router = express.Router();
var mongo = require('mongodb')
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/productso";
var upload = require('./photos');
router.use(function (req, res, next) {
// do logging
// do authentication
console.log('Logging of request url -> '+req.url);
next(); // make sure we go to the next routes and don't stop here
})
router.route('/greet').get(function(req, res){
res.send('Hello World');
})
router.route('/addImage').post(upload.single("photo"),
function(req, res) {
let imageUrl = {
imageUrl: req.file.filename,
};
res.send(imageUrl);
})
router.route('/image/:filename').get(function (req, res) {
var url = req.url;
var mfilename = url.substring(url.lastIndexOf('/') + 1);
console.log(mfilename);
var filePath = path.join(__dirname, 'images', mfilename);
const r = fs.createReadStream(filePath) // or any other way to get a readable stream
const ps = new stream.PassThrough() // <---- this makes a trick with stream error handling
stream.pipeline(
r,
ps, // <---- this makes a trick with stream error handling
(err) => {
if (err) {
console.log(err) // No such file or any other kind of error
return res.sendStatus(400);
}
})
ps.pipe(res) // <---- this makes a trick with stream error handling
})
router.route('/list').get(function(req,res) {
try{
MongoClient.connect(url,
function(err, db) {
if (err) throw err;
console.log("Database connected!");
var dbo = db.db("productso");
var results = dbo.collection("products").find({}).toArray(function(err, result) {
if (err) throw err;
// console.log(result);
res.send(result);
db.close();
});
var count = dbo.collection("products").find({}).count(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
}catch(err){
console.log(err);
}
})
router.route('/create').post(function(req,res) {
console.log(req.body);
MongoClient.connect(url,
function(err, db) {
if (err) throw err;
console.log("Database connected!");
var dbo = db.db("productso");
var title = req.body[0].title;
var price = req.body[0].price;
var stockamount = req.body[0].stockamount;
var instock = "false";
if(parseInt(stockamount)>0){
instock = "true";
}
var photo = req.body[0].photo;
var photoUrl = req.body[0].imageUrl;
//var code = req.body[0].productCode;
var guid = (title.trim().substr(0,3).toUpperCase()) + (Math.random()*1000000).toString().substr(0,4);
var rating = req.body[0].rating;
var description = req.body[0].description;
console.log(instock);
dbo.collection("products").insertOne({productCode: guid, rating: rating, description: description, title:title, price:price, stockamount: stockamount, instock: instock, photo:photo, photoUrl: photoUrl}, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
db.close();
});
});
})
router.route('/findbyprice').post(function(req, res){
console.log(req.body);
try {
MongoClient.connect(url,
function(err, db) {
if (err) throw err;
console.log("Database connected!");
var price = req.body[0].price;
var dbo = db.db("productso");
var results = dbo.collection("products").find({ price: new RegExp(price, 'i')}).toArray(function(err, result) {
if (err) throw err;
res.send(result);
db.close();
})
});
}catch(err){
console.log(err);
}
})
router.route('/findbyid').post(function(req, res){
try{
console.log(req.body[0].id);
MongoClient.connect(url,
function(err, db) {
if (err) throw err;
console.log("Database connected!");
var id = req.body[0].id;
var dbo = db.db("productso");
var results = dbo.collection("products").find({ productCode: id}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
res.send(result);
db.close();
})
});
}catch(err){
console.log(err);
}
})
router.route('/edit').post(function(req, res) {
console.log('---------------------------------------')
console.log(req.body);
try{
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("productso");
var id = req.body[0].id;
console.log(id);
var title = req.body[0].title;
var price= req.body[0].price;
var stockamount = req.body[0].stockamount;
var instock = "false";
if(parseInt(stockamount)>0){
instock = "true";
}
var photo= req.body[0].photo;
var rating = req.body[0].rating;
var description = req.body[0].description;
var photoUrl = req.body[0].photoUrl;
var myquery = {_id: new mongo.ObjectID(id)};
var newvalues = { $set : {rating: rating, description: description, title:title, price:price, stockamount: stockamount, instock: instock, photo:photo, photoUrl: photoUrl}};
dbo.collection("products").findOneAndUpdate(myquery, newvalues, function(err, res) {
if (err) throw err;
console.log("1 document updated");
db.close();
});
});
}catch(err){
console.log(err);
}
})
router.route('/delete/:id').delete(function(req, res){
try {
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("productso");
var id = req.url.split('/');
var myobj = id[2].toString();
dbo.collection("products").deleteOne({_id: new mongo.ObjectID(myobj)}, function(err, results) {
if (err){console.log("failed");throw err;}
console.log("1 document deleted");
res.send("1 document(s) deleted");
db.close();
});
});
}catch(e){
console.log(e);
}
})
router.route('/abcd').get(function(req,res) {
let product = {
title: 'pen',
price: 10
};
res.send(product);
})
router.route('/abc').post(function(req,res) {
console.log(JSON.stringify(req.body));
var title = req.body[0].title;
console.log(title);
})
app.use(cors());
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'x-www-form-urlencoded, Origin, X-Requested-With, Content-Type, Accept, Authorization, *');
if (req.method === 'OPTIONS'){
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, PATCH, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Credentials', true);
return res.status(200).json({});
}
req.setTimeout(3600000);
if (req.method === 'OPTIONS') {
res.write(':)');
res.end();
} else next();
});
app.use('/api', router);
app.listen(port);
console.log('REST API is runnning at ' + port);
/*[{"productCode": "ABC123", "title": "No onion", "rating": "4.5", "description": "A great product", "price": "555", instock: "true", "photo": "null"}]*/