-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathapp.js
86 lines (68 loc) · 2.14 KB
/
app.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
const express = require('express');
const data = require('./data.json');
const app = express();
const PORT = process.env.PORT || 8080;
const { data: jsonData } = data;
app.get('/', (req, res) => {
const response = {
greeting: "Hey, Buddy! Welcome to the StudentAI API",
statusCode: res.statusCode
};
res.json(response);
});
const paginationMiddleware = () => {
return (req, res, next) => {
const pageNumber = +req.query.page || 1;
const pageSize = parseInt(req.query.limit) || 50;
const startIndex = (pageNumber - 1) * pageSize;
const endIndex = startIndex + pageSize;
req.pagination = {
page: pageNumber,
limit: pageSize,
startIndex,
endIndex
};
next();
};
};
app.get('/search', paginationMiddleware(), (req, res) => {
const { startIndex, endIndex } = req.pagination;
const searchText = req.query.apps;
const filters = req.query.filters;
const filterArray = filters?.split(',') || ['title'];
let searchResults = searchText
? jsonData.filter((item) => {
return filterArray.every(filterTerm => item[filterTerm].toLowerCase().includes(searchText.toLowerCase()));
})
: jsonData.slice(startIndex, endIndex);
searchResults = searchResults.slice(startIndex, endIndex);
const response = {
result: searchResults.map(({ id, icon, color, title, disc }) => (
{
id,
icon,
color,
title,
disc
}))
};
res.json(response);
});
app.get('/id/:id', (req, res) => {
const requestedId = req.params.id.toLowerCase();
const searchResult = jsonData.find((item) => item.id === requestedId);
if (!searchResult) {
res.status(404).json({ error: 'ID not found' });
return;
}
const response = {
result: searchResult
};
res.json(response);
});
app.get('*', function (req, res) {
res.status(500).json({ error: 'Details not found!' });
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});