-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
318 lines (254 loc) · 9.49 KB
/
Copy pathapp.js
File metadata and controls
318 lines (254 loc) · 9.49 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
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
require("dotenv").config();
const express = require('express');
const path=require('path');
const { MongoClient } = require('mongodb');
const { link } = require("fs");
const cors=require("cors");
const uri = process.env.MONGODBatlas_URL;
const dbName = "Project1";
const collectionName = "FakeAPI";
async function main() {
const app = express();
const PORT =process.env.PORT || 3000;
const client = new MongoClient(uri);
app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/',(req,res)=>{
res.sendFile(path.join(__dirname, 'public', 'index.html'));
})
app.get('/docs',(req,res)=>{
res.sendFile(path.join(__dirname, 'public', 'docs.html'));
})
try {
await client.connect();
console.log("Connected successfully to MongoDB Atlas");
const db = client.db(dbName);
const collection = db.collection(collectionName);
// app.get('/data', async (req, res) => {
// try {
// // Default pagination values
// const page = parseInt(req.query.page) || 1;
// const limit = parseInt(req.query.limit) || 28;
// const category = req.query.category || 'all';
// const subCategory = req.query.subCategory || 'all';
// if (isNaN(page) || page < 1 || isNaN(limit) || limit < 1) {
// return res.status(400).json({ error: 'Invalid page or limit value.' });
// }
// const skip = (page - 1) * limit;
// let query = {};
// // Handle category and subcategory filtering
// if (category !== 'all') {
// query['categories.category'] = category;
// }
// if (subCategory !== 'all') {
// query['categories.sub_category'] = subCategory;
// }
// const total = await collection.countDocuments(query);
// const data = await collection.find(query).skip(skip).limit(limit).toArray();
// const totalPages = Math.ceil(total / limit);
// res.json({
// data,
// total,
// page,
// totalPages
// });
// } catch (err) {
// console.error("Error fetching paginated data:", err);
// res.status(500).send("Internal Server Error");
// }
// });
//TO FETCH ALL RECORDS
app.get('/data', async (req, res) => {
try {
const data = await collection.find({}).toArray();
res.json(data);
} catch (err) {
console.error("Error fetching data:", err);
res.status(500).send("Internal Server Error");
}
});
// TO FETCH RECORDS WITH PAGINATION
app.get(`/data/limit`, async (req, res) => {
try {
// Get page and limit from query params (default to page 1, limit 25)
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 28;
const category = req.query.category;
// Basic validation for page and limit
if (isNaN(page) || page < 1 || isNaN(limit) || limit < 1) {
return res.status(400).json({ error: 'Invalid page or limit value.' });
}
// Calculate skip (how many documents to skip)
const skip = (page - 1) * limit;
let query={};
if(category&&category!=='all'){
query={'categories.category':category};
}
// Total number of documents
const total = await collection.countDocuments(query);
// Fetch documents with skip and limit
const data = await collection.find(query)
.skip(skip)
.limit(limit)
.toArray();
const totalPages = Math.ceil(total / limit);
res.json({
data,
total,
page,
totalPages
});
} catch (err) {
console.error("Error fetching paginated data:", err);
res.status(500).send("Internal Server Error");
}
});
//TO FETCH RECORD ACCORDING TO ID
app.get('/data/:id', async (req, res) => {
const id = parseInt(req.params.id);
if (isNaN(id)) {
return res.status(400).json({ error: 'Invalid ID format. ID must be an integer.' });
}
try {
const item = await collection.findOne({ id: id });
if (item) {
res.json(item);
} else {
res.status(404).json({ error: 'Data not found' });
}
} catch (error) {
console.error('Error fetching data by ID:', error);
res.status(500).json({ error: 'Failed to fetch data' });
}
});
//TO FETCH ALL CATEGORIES
app.get('/api/categories', async (req, res) => {
try {
const distinctCategories = await collection.distinct('categories.category');
if (distinctCategories.length > 0) {
res.json(distinctCategories);
} else {
res.status(404).json({ error: 'No categories found' });
}
} catch (error) {
console.error('Error fetching distinct categories:', error);
res.status(500).json({ error: 'Failed to fetch categories' });
}
});
//TO FETCH ALL SUB-CATEGORIES
app.get('/api/sub-categories', async (req, res) => {
try {
const distinctsubCategories = await collection.distinct('categories.sub-category');
if (distinctsubCategories.length > 0) {
res.json(distinctsubCategories);
} else {
res.status(404).json({ error: 'No sub-category found' });
}
} catch (error) {
console.error('Error fetching distinct sub-categories:', error);
res.status(500).json({ error: 'Failed to fetch sub-categories' });
}
});
//TO FETCH RECORDS ACCORDING TO CATEGORY
app.get('/data/category/:category', async (req, res) => {
const category = req.params.category;
try {
const data = await collection.find({ 'categories.category': category }).toArray();
if (data.length > 0) {
res.json(data);
} else {
res.status(404).json({ error: `No data found for category: ${category}` });
}
} catch (error) {
console.error('Error fetching data by category:', error);
res.status(500).json({ error: 'Failed to fetch data' });
}
});
//TO FETCH RECORDS ACCORDING TO CATEGORY AND SUB-CATEGORY
app.get('/data/category/:category/sub-category/:subcategory', async (req, res) => {
const category = req.params.category;
const subcategory = req.params.subcategory;
try {
const data = await collection.find({
'categories.category': category,
'categories.sub-category': subcategory
}).toArray();
if (data.length > 0) {
res.json(data);
} else {
res.status(404).json({
error: `No data found for category: ${category} and sub-category: ${subcategory}`
});
}
} catch (error) {
console.error('Error fetching data by category and sub-category:', error);
res.status(500).json({ error: 'Failed to fetch data' });
}
});
//TO INSERT A NEW RECORD INTO THE COLLECTION
app.post('/data', express.json(), async (req, res) => {
try {
const newData = req.body;
const result = await collection.insertOne(newData);
res.status(201).json(result);
} catch (err) {
console.error("Error inserting data:", err);
res.status(500).send("Internal Server Error");
}
});
//TO UPDATE A RECORD IN THE COLLECTION PARTIALLY OR COMPLETELY
app.put('/data/:id', express.json(), async (req, res) => {
try {
const idFromUrl = req.params.id;
const updateData = req.body;
if (updateData.id !== parseInt(idFromUrl)) {
return res.status(400).json({ error: 'ID in request body does not match ID in URL.' });
}
const result = await collection.updateOne({ id: parseInt(idFromUrl) }, {$set: updateData});
res.json(result);
} catch (err) {
console.error("Error updating data:", err);
res.status(500).send("Internal Server Error");
}
});
//TO UPDATE A RECORD IN THE COLLECTION PARTIALLY
app.patch('/data/:id', express.json(), async (req, res) => {
try {
const idFromUrl = req.params.id;
const updateData = req.body;
if (updateData.id !== parseInt(idFromUrl)) {
return res.status(400).json({ error: 'ID in request body does not match ID in URL.' });
}
const result = await collection.updateOne({ id: parseInt(idFromUrl) }, {$set: updateData});
res.json(result);
} catch (err) {
console.error("Error updating data:", err);
res.status(500).send("Internal Server Error");
}
});
//TO DELETE A RECORD FROM THE COLLECTION
app.delete('/data/:id', async (req, res) => {
const id = parseInt(req.params.id); // Assuming 'id' in your data is an integer
// Optional: Basic validation to ensure 'id' is a number
if (isNaN(id)) {
return res.status(400).json({ error: 'Invalid ID format. ID must be an integer.' });
}
try {
const item = await collection.deleteOne({ id: id }); // Querying to delete one collection
if (item) {
res.json(item);
} else {
res.status(404).json({ error: 'Data not found' });
}
} catch (error) {
console.error('Error fetching data by ID:', error);
res.status(500).json({ error: 'Failed to fetch data' });
}
});
app.listen(PORT,'0.0.0.0', () => {
console.log(`Server listening at http://localhost:${PORT}`);
});
} finally {
}
}
main().catch(console.error);