From 4d8fb8e5a3e926e8d56ee79e76639f3dd1ed13a3 Mon Sep 17 00:00:00 2001 From: AdisakKanthawilang Date: Thu, 22 Feb 2024 16:32:13 +0700 Subject: [PATCH] =?UTF-8?q?=E0=B9=80=E0=B8=9E=E0=B8=B4=E0=B9=88=E0=B8=A1?= =?UTF-8?q?=20paginate=20=E0=B9=81=E0=B8=A5=E0=B8=B0=20keyword=20org=5F065?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/controllers/ProfileController.ts | 57 ++++++++++++++++++++++++---- 1 file changed, 50 insertions(+), 7 deletions(-) diff --git a/src/controllers/ProfileController.ts b/src/controllers/ProfileController.ts index b54d8feb..d5fb8c85 100644 --- a/src/controllers/ProfileController.ts +++ b/src/controllers/ProfileController.ts @@ -12,6 +12,7 @@ import { SuccessResponse, Response, Get, + Query, } from "tsoa"; import { AppDataSource } from "../database/data-source"; import HttpSuccess from "../interfaces/http-success"; @@ -254,8 +255,12 @@ export class ProfileController extends Controller { * */ @Get() - async listProfile() { - const profile = await this.profileRepository.find({ + async listProfile( + @Query("page") page: number = 1, + @Query("pageSize") pageSize: number = 10, + @Query("keyword") keyword?: string, + ) { + const [profile, total] = await this.profileRepository.findAndCount({ select: [ "id", "prefix", @@ -267,16 +272,54 @@ export class ProfileController extends Controller { "posTypeId", ], order: { createdAt: "ASC" }, + skip: (page - 1) * pageSize, + take: pageSize, }); + if (keyword != undefined && keyword !== "") { + const formattedKeyword = keyword.toLowerCase().replace(/\s+/g, ""); + const filteredProfile = profile.filter( + (x) => + ( + x.prefix + + x.firstName + + x.lastName + ) + .replace(/\s+/g, "") + .includes(formattedKeyword) || + x.citizenId?.toString().includes(keyword) || + x.position?.toString().includes(keyword) + ); + + const formattedData = filteredProfile.map((item) => ({ + id: item.id, + prefix: item.prefix, + firstName: item.firstName, + lastName: item.lastName, + citizenId: item.citizenId, + position: item.position, + posLevelId: item.posLevelId, + posTypeId: item.posTypeId + })); + + return new HttpSuccess({ data: formattedData, total: formattedData.length }); + } if (!profile) { return new HttpSuccess([]); } - try { - return new HttpSuccess(profile); - } catch (error) { - return error; - } + + const formattedData = profile.map((item) => ({ + id: item.id, + prefix: item.prefix, + firstName: item.firstName, + lastName: item.lastName, + citizenId: item.citizenId, + position: item.position, + posLevelId: item.posLevelId, + posTypeId: item.posTypeId + })); + return new HttpSuccess({ data: formattedData, total }); + } /**