2
2
3
3
import Fastify from 'fastify' ;
4
4
5
-
6
5
// logger
7
6
import pino from 'pino' ;
8
7
import pretty from 'pino-pretty' ;
@@ -65,16 +64,24 @@ import wordsData from './data/words.js';
65
64
* @param {number } limit - The limit of items per page.
66
65
* @return {Object } An object containing paginated data, current page, limit, total data count, total pages.
67
66
*/
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
69
76
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 ) ;
73
80
74
81
return {
75
82
page,
76
83
limit,
77
- total : data . length ,
84
+ total : filteredData . length ,
78
85
totalPages,
79
86
data : paginatedData ,
80
87
} ;
@@ -86,6 +93,7 @@ const paginationSchema = {
86
93
properties : {
87
94
page : { type : 'integer' , minimum : 1 , default : 1 } ,
88
95
limit : { type : 'integer' , minimum : 1 , maximum : 100 , default : 10 } ,
96
+ search : { type : 'string' , default : '' } ,
89
97
} ,
90
98
} ,
91
99
} ;
@@ -100,12 +108,11 @@ const paginationSchema = {
100
108
*/
101
109
function createRoute ( path , data , opts ) {
102
110
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 ) ;
105
113
} ) ;
106
114
}
107
115
108
-
109
116
app . get ( '/' , ( request , reply ) => {
110
117
const protocol = process . env . NODE_ENV === 'development' ? 'http' : 'https' ;
111
118
const baseUrl = `${ protocol } ://${ request . headers . host } ` ;
@@ -135,7 +142,6 @@ createRoute('/prompts', promptsData, { schema: paginationSchema });
135
142
createRoute ( '/series' , seriesData , { schema : paginationSchema } ) ;
136
143
createRoute ( '/words' , wordsData , { schema : paginationSchema } ) ;
137
144
138
-
139
145
if ( process . env . NODE_ENV === 'development' ) {
140
146
/**
141
147
* A function that asynchronously starts the application listening on port 3000.
0 commit comments