From 876e3b3d0c94f2927decad7d1209e3fccf1a7961 Mon Sep 17 00:00:00 2001 From: Emma Indal Date: Fri, 30 Sep 2022 16:07:54 +0200 Subject: [PATCH] Accept resultsPerPage param on the search query Co-authored-by: Camila Loiola Signed-off-by: Emma Indal --- .../search-backend/src/service/router.test.ts | 18 ++++++++++++++++++ plugins/search-backend/src/service/router.ts | 12 ++++++++++++ plugins/search-common/src/types.ts | 1 + 3 files changed, 31 insertions(+) diff --git a/plugins/search-backend/src/service/router.test.ts b/plugins/search-backend/src/service/router.test.ts index f26f191ecd..3b29e57969 100644 --- a/plugins/search-backend/src/service/router.test.ts +++ b/plugins/search-backend/src/service/router.test.ts @@ -112,6 +112,24 @@ describe('createRouter', () => { }); }); + it('should accept per page value under or equal to 100', async () => { + const response = await request(app).get(`/query?resultsPerPage=30`); + + expect(response.status).toEqual(200); + expect(response.body).toMatchObject({ + results: [], + }); + }); + + it('should reject per page value over 100', async () => { + const response = await request(app).get(`/query?resultsPerPage=200`); + + expect(response.status).toEqual(400); + expect(response.body).toMatchObject({ + error: { message: /The maximum value of the resultsPerPage param is 100, please update and make a new request/i }, + }); + }); + it('removes backend-only properties from search documents', async () => { mockSearchEngine.query.mockResolvedValue({ results: [ diff --git a/plugins/search-backend/src/service/router.ts b/plugins/search-backend/src/service/router.ts index 87da80d8f5..c0b6661f78 100644 --- a/plugins/search-backend/src/service/router.ts +++ b/plugins/search-backend/src/service/router.ts @@ -71,6 +71,7 @@ export async function createRouter( options: RouterOptions, ): Promise { const { engine: inputEngine, types, permissions, config, logger } = options; + const MAX_RESULT_PER_PAGE = 100 const requestSchema = z.object({ term: z.string().default(''), @@ -79,6 +80,17 @@ export async function createRouter( .array(z.string().refine(type => Object.keys(types).includes(type))) .optional(), pageCursor: z.string().optional(), + resultsPerPage: z + .string() + .transform((resultsPerPage) => parseInt(resultsPerPage)) + .refine( + resultsPerPage => resultsPerPage <= MAX_RESULT_PER_PAGE, + resultsPerPage => ({ + message: + `The maximum value of the resultsPerPage param is ${MAX_RESULT_PER_PAGE}, you provided ${resultsPerPage}, please update and make a new request`, + }), + ) + .optional(), }); let permissionEvaluator: PermissionEvaluator; diff --git a/plugins/search-common/src/types.ts b/plugins/search-common/src/types.ts index 4b4c25d423..1daced8e5b 100644 --- a/plugins/search-common/src/types.ts +++ b/plugins/search-common/src/types.ts @@ -26,6 +26,7 @@ export interface SearchQuery { filters?: JsonObject; types?: string[]; pageCursor?: string; + resultsPerPage?: number; } /**