Skip to content

Commit 42abefa

Browse files
committed
feat: add search ability through /xxx?search=CONTENT_TO_BE_SEARCH
1 parent 5a6c946 commit 42abefa

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

server.js

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import Fastify from 'fastify';
44

5-
65
// logger
76
import pino from 'pino';
87
import pretty from 'pino-pretty';
@@ -65,16 +64,24 @@ import wordsData from './data/words.js';
6564
* @param {number} limit - The limit of items per page.
6665
* @return {Object} An object containing paginated data, current page, limit, total data count, total pages.
6766
*/
68-
function getPaginatedData(data, page, limit) {
67+
function getPaginatedData(data, searchTerm, page, limit) {
68+
// Filter data if searchTerm is provided
69+
const filteredData = searchTerm
70+
? data.filter((item) =>
71+
JSON.stringify(item).toLowerCase().includes(searchTerm.toLowerCase())
72+
)
73+
: data;
74+
75+
// Calculate pagination as before
6976
const startIndex = (page - 1) * limit;
70-
const endIndex = Math.min(startIndex + limit, data.length);
71-
const paginatedData = data.slice(startIndex, endIndex);
72-
const totalPages = Math.ceil(data.length / limit);
77+
const endIndex = Math.min(startIndex + limit, filteredData.length);
78+
const paginatedData = filteredData.slice(startIndex, endIndex);
79+
const totalPages = Math.ceil(filteredData.length / limit);
7380

7481
return {
7582
page,
7683
limit,
77-
total: data.length,
84+
total: filteredData.length,
7885
totalPages,
7986
data: paginatedData,
8087
};
@@ -86,6 +93,7 @@ const paginationSchema = {
8693
properties: {
8794
page: { type: 'integer', minimum: 1, default: 1 },
8895
limit: { type: 'integer', minimum: 1, maximum: 100, default: 10 },
96+
search: { type: 'string', default: '' },
8997
},
9098
},
9199
};
@@ -100,12 +108,11 @@ const paginationSchema = {
100108
*/
101109
function createRoute(path, data, opts) {
102110
app.get(path, { schema: opts.schema }, async (request, reply) => {
103-
const { page, limit } = request.query;
104-
return getPaginatedData(data, page, limit);
111+
const { page, limit, search } = request.query;
112+
return getPaginatedData(data, search, page, limit);
105113
});
106114
}
107115

108-
109116
app.get('/', (request, reply) => {
110117
const protocol = process.env.NODE_ENV === 'development' ? 'http' : 'https';
111118
const baseUrl = `${protocol}://${request.headers.host}`;
@@ -135,7 +142,6 @@ createRoute('/prompts', promptsData, { schema: paginationSchema });
135142
createRoute('/series', seriesData, { schema: paginationSchema });
136143
createRoute('/words', wordsData, { schema: paginationSchema });
137144

138-
139145
if (process.env.NODE_ENV === 'development') {
140146
/**
141147
* A function that asynchronously starts the application listening on port 3000.

0 commit comments

Comments
 (0)