-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExercises.js
More file actions
101 lines (89 loc) · 2.56 KB
/
Exercises.js
File metadata and controls
101 lines (89 loc) · 2.56 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
const axios = require('axios');
const config = (url, params = {}) => ({
method: 'get',
url,
headers: { 'Content-Type': 'application/json' },
params,
});
const fetchProducts = (req, res) => {
const url = 'https://api.mercadolibre.com/sites/MLA/search';
const params = {};
if (req.query && req.query.q) {
params.q = req.query.q;
}
axios(config(url, params))
.then((results) => {
const categories = [
...new Set(results.data.results.map((product) => product.category_id)),
];
const items = results.data.results.map((product) => {
const priceParsed = product.price.toString().split('.');
return {
id: product.id,
title: product.title,
price: {
currency: product.currency_id,
amount: priceParsed[0],
decimals: priceParsed[1] || '',
},
picture: product.thumbnail,
condition: product.condition,
free_shipping: product.shipping.free_shipping,
};
});
const ret = {
author: {
name: 'Azlain',
lastname: 'Saavedra',
},
categories,
items,
};
res.send(ret);
})
.catch((error) => {
console.log(error);
res.send(error);
});
};
const fetchProduct = (req, res) => {
const urlProduct = `https://api.mercadolibre.com/items/${req.params.id}`;
const urlProductDescription = `https://api.mercadolibre.com/items/${req.params.id}/description`;
const reqProduct = axios(config(urlProduct));
const reqProductDescription = axios(config(urlProductDescription));
Promise.all([reqProduct, reqProductDescription])
.then((results) => {
const product = results[0].data;
const productDescription = results[1].data;
const priceParsed = product.price.toString().split('.');
const ret = {
author: {
name: 'Azlain',
lastname: 'Saavedra',
},
item: {
id: product.id,
title: product.title,
price: {
currency: product.currency_id,
amount: priceParsed[0],
decimals: priceParsed[1] || '',
},
picture: product.thumbnail,
condition: product.condition,
free_shipping: product.shipping.free_shipping,
sold_quantity: product.sold_quantity,
description: productDescription.plain_text,
},
};
res.send(ret);
})
.catch((error) => {
console.log(error);
res.send(error);
});
};
module.exports = {
fetchProducts,
fetchProduct,
};