forked from ThomasRivoal/clear-fashion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.js
102 lines (75 loc) · 2.54 KB
/
api.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
const cors = require('cors');
const express = require('express');
const helmet = require('helmet');
const { ObjectId } = require('mongodb');
const db = require('./db');
const { calculateLimitAndOffset, paginate } = require('paginate-info');
const PORT = 8092;
const app = express();
module.exports = app;
async function connection(){
await db.connect();
}
app.use(require('body-parser').json());
app.use(cors());
app.use(helmet());
app.options('*', cors());
var products = "";
console.log(`📡 Running on port ${PORT}`);
// All products
app.get('/products', async(request, response) => {
await connection();
const filters = request.query;
const count = await db.countDocumentsDb();
const { limit, offset } = calculateLimitAndOffset(parseInt(filters.page), parseInt(filters.size));
var products = await db.findProducts({}, offset, limit, false);
const meta = paginate(parseInt(filters.page), count, products, parseInt(filters.size));
response.send(
{
"success" : true,
"data" : {
"result" : products,
"meta" : meta
}
}
);
})
// Product search, Search for specific product
app.get('/products/search', async(request, response) => {
const filters = request.query;
console.log('filters :>> ', filters);
const brand = filters.brand !== undefined ? filters.brand : ''
const price = parseInt(filters.price,10) > 0 ? parseInt(filters.price,10) : ''
const limit = parseInt(filters.limit,10) > 0 ? parseInt(filters.limit,10) : 12
var match = {}
if( brand === '' && price !== '') match = {price: price}
else if(brand !== '' && price === '') match = {brand: brand}
else if(brand !== '' && price !== '') match = {brand: brand, price: price}
query = [
{'$match' : match},
{'$sort' : {price:1}},
{'$limit' : limit}
]
console.log('query :>> ', query);
var filteredProducts = await db.aggregateQuery(query)
console.log('filteredProducts.length :>> ', filteredProducts.length);
response.send(filteredProducts);
})
// Products by id
app.get('/products/:_id', async(request, response) => {
products = await db.findProducts({'_id': new ObjectId(request.params._id)}, false)
response.send({"count" : products.length, "products" : products});
})
// Products by brand
app.get('/products/brand=', async(request, response) => {
products = await db.findProducts({'brand': 'adresse'}, false)
console.log(products.length)
response.send({"products" : products});
})
async function main(){
await connection();
app.listen(PORT);
//await request();
//await db.close();
}
main();