-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
181 lines (161 loc) · 5.38 KB
/
index.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
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import axios from 'axios';
import { getConnection } from './models/dbModel.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/api/products', (req, res) => {
getConnection().then(conn => {
conn.query('SELECT * FROM products')
.then(rows => {
if (rows.length > 0) {
res.json(rows);
} else {
axios.get('https://fakestoreapi.com/products').then(apiResponse => {
let queryData = [];
apiResponse.data.forEach((element) => {
queryData.push([element.id, element.price, element.title, element.category, element.description, element.image]);
});
getConnection().then(conn => {
conn.batch(`INSERT INTO products (id, price, title, category, description, image) VALUES (?, ?, ?, ?, ?, ?)`, queryData)
.then(() => {
res.json(apiResponse.data);
})
.catch(err => {
console.log(err);
res.status(500).send('Error inserting products into database');
});
}).finally(() => {
conn.end();
})
}).catch(err => {
console.log(err);
res.status(500).send('Error retrieving products from API');
});
}
})
.catch(err => {
console.log(err);
res.status(500).send('Error retrieving products from database');
})
.finally(() => {
conn.end();
});
})
});
app.get('/api/products/id/:id', (req, res) => {
const productId = req.params.id;
getConnection().then(conn => {
conn.query('SELECT * FROM products WHERE id = ?', [productId])
.then(rows => {
if (rows.length > 0) {
res.json(rows[0]);
} else {
res.status(404).send('Product not found');
}
})
.catch(err => {
console.log(err);
res.status(500).send('Error retrieving product from database');
})
.finally(() => {
conn.end();
});
})
});
app.get('/api/products/count', (req, res) => {
const { count = 10, offset = 0 } = req.query;
if ( isNaN(parseInt(count)) || count < 1 || count > 100 ) {
return res.status(400).send('Count parameter must be a positive integer between 1 and 100');
}
if (isNaN(parseInt(offset)) || offset < 0 || !isFinite(offset)) {
return res.status(400).send('Offset parameter must be a positive integer');
}
getConnection().then(conn => {
conn.query('SELECT * FROM products LIMIT ? OFFSET ?', [parseInt(count), parseInt(offset)])
.then(rows => {
if (rows.length > 0) {
res.json(rows);
} else {
res.status(404).send('No products found. SQL response: ' + rows);
}
})
.catch(err => {
console.log(err);
res.status(500).send('Error retrieving products from database');
})
.finally(() => {
conn.end();
});
})
})
app.get('/api/products/category/count', (req, res) => {
const { category, count = 10, offset = 0, exclude = false } = req.query;
if (!category) {
return res.status(400).send('Category parameter is required');
}
if ( isNaN(parseInt(count)) || count < 1 || count > 100 ) {
return res.status(400).send('Count parameter must be a positive integer between 1 and 100');
}
if (isNaN(parseInt(offset)) || offset < 0 || !isFinite(offset)) {
return res.status(400).send('Offset parameter must be a positive integer');
}
getConnection().then(conn => {
conn.query('SELECT * FROM products WHERE category = ? AND id NOT IN (?) LIMIT ? OFFSET ?', [category, JSON.parse(exclude), parseInt(count), parseInt(offset)])
.then(rows => {
if (rows.length > 0) {
res.json(rows);
} else {
res.status(404).send('No products found in this category: ' + category +". SQL response: " + rows);
}
})
.catch(err => {
console.log(err);
res.status(500).send('Error retrieving product from database');
})
.finally(() => {
conn.end();
});
})
});
app.get('/api/categories/', (req, res) => {
getConnection().then(conn => {
conn.query('SELECT category, COUNT(*) AS count FROM products GROUP BY category')
.then(rows => {
if (rows.length > 0) {
res.json(
rows.map((row) => ({
category: row.category,
count: row.count.toString(),
})));
} else {
res.status(404).send('No categories found');
}
})
.catch(err => {
console.log(err);
res.status(500).send('Error retrieving categories from database');
})
.finally(() => {
conn.end();
});
})
});
app.get('/cart', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.get('/favorites', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.use(express.static(path.join(__dirname, "public")));
app.use((req, res, next) => {
res.status(404).send(
"Page not found on the server. Please check the URL and try again."
)
})
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});