Skip to content

Commit

Permalink
* Refactored search/internal endpoint. (#177)
Browse files Browse the repository at this point in the history
* Removed search/internal endpoint.
* Added functionality to sort search by field.
  • Loading branch information
chinmoy12c authored Jul 31, 2023
1 parent e1c7e33 commit eb4377d
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 86 deletions.
14 changes: 14 additions & 0 deletions src/modules/bot/bot.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,4 +267,18 @@ describe('BotController', () => {
expect(resp).toBeTruthy();
updateParametersPassed = [];
})

it('search throws error on unknown search fields', async () => {
expect(botController.search(
'1',
'1',
'',
'',
'true',
'nonExistent',
{}
))
.rejects
.toThrowError(new BadRequestException(`sorting by 'nonExistent' is not supported!`));
});
});
59 changes: 27 additions & 32 deletions src/modules/bot/bot.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,50 +118,45 @@ export class BotController {
AddOwnerInfoInterceptor,
AddROToResponseInterceptor,
)
find(
@Query('perPage') perPage: string,
@Query('page') page: string,
async search(
@Query('perPage') perPage: string | undefined,
@Query('page') page: string | undefined,
@Query('name') name: string,
@Query('startingMessage') startingMessage: string,
@Query('match') match: 'true' | 'false',
@Query('sortBy') sortBy: string | undefined,
@Body() body: any,
) {
if (!perPage) perPage = '10';
if (!page) page = '1';
return this.botService.find(
parseInt(perPage),
parseInt(page),
name,
startingMessage,
match === 'true',
body.ownerId,
body.ownerOrgId,
);
}

@Get('/search/internal')
@UseInterceptors(
AddResponseObjectInterceptor,
AddAdminHeaderInterceptor,
AddOwnerInfoInterceptor,
AddROToResponseInterceptor,
)
findForAdmin(
@Query('perPage') perPage: string,
@Query('page') page: string,
@Query('name') name: string,
@Query('startingMessage') startingMessage: string,
@Query('match') match: 'true' | 'false',
@Body() body: any,
) {
return this.botService.findForAdmin(
if (!perPage) {
this.logger.log('perPage not provided, defaulting to 10.');
perPage = '10';
}
if (!page) {
this.logger.log('page not provided, defaulting to 1.');
page = '1';
}
const allowedSortingFields = [
"startingMessage",
"name",
"status",
"createdDate",
"endDate",
"ownerid",
"ownerorgid",
];
if (sortBy && !allowedSortingFields.includes(sortBy)) {
this.logger.error(`sorting by '${sortBy}' is not supported!`);
throw new BadRequestException(`sorting by '${sortBy}' is not supported!`);
}
return await this.botService.search(
parseInt(perPage),
parseInt(page),
name,
startingMessage,
match === 'true',
body.ownerId,
body.ownerOrgId,
sortBy,
);
}

Expand Down
25 changes: 22 additions & 3 deletions src/modules/bot/bot.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,13 @@ const MockPrismaService = {
}
return JSON.parse(JSON.stringify(mockBotsDb[0]));
},
findMany: () => {
return JSON.parse(JSON.stringify(mockBotsDb));
findMany: (filter) => {
if (filter.orderBy && filter.orderBy.sortParameter) {
return 'sortedBots';
}
else {
return JSON.parse(JSON.stringify(mockBotsDb));
}
},
update: jest.fn()
}
Expand Down Expand Up @@ -496,7 +501,7 @@ describe('BotService', () => {
.toThrowError(new NotFoundException('Bot does not exist!'));
})

it('bot update calls prisma update',async () => {
it('bot update calls prisma update', async () => {
fetchMock.getOnce(`${configService.get<string>('MINIO_GET_SIGNED_FILE_URL')}/?fileName=testImageFile`,
'testImageUrl'
);
Expand All @@ -518,4 +523,18 @@ describe('BotService', () => {
.toThrowError(new BadRequestException(`Bad date format. Please provide date in 'yyyy-mm-dd' format.`));
fetchMock.restore();
})

it('bot update passes orderBy parameter to search', async () => {
const resp = await botService.search(
1,
1,
'',
'',
true,
'',
'',
'sortParameter'
);
expect(resp).toEqual({"data": "sortedBots", "totalCount": 10});
})
});
64 changes: 13 additions & 51 deletions src/modules/bot/bot.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -371,20 +371,18 @@ export class BotService {
});
}

async find(
async search(
perPage: number,
page: number,
name: string,
startingMessage: string,
match: boolean,
ownerID: string,
ownerOrgID: string,
sortBy: string | undefined,
): Promise<{ data: Bot[]; totalCount: number } | null> {
const startTime = performance.now();
let filterQuery: any = {
ownerID: ownerID,
ownerOrgID: ownerOrgID,
};
let filterQuery: any = {};
if (name || startingMessage) {
filterQuery.OR = [
{
Expand All @@ -397,60 +395,24 @@ export class BotService {
},
];
}
if (!ownerID || !ownerOrgID) {
delete filterQuery.ownerID;
delete filterQuery.ownerOrgID;
filterQuery.OR = [
{
name: match ? name : caseInsensitiveQueryBuilder(name),
},
{
startingMessage: match
? startingMessage
: caseInsensitiveQueryBuilder(startingMessage),
},
];
if (ownerID || ownerOrgID) {
filterQuery.ownerID = ownerID;
filterQuery.ownerOrgID = ownerOrgID;
}
if (!sortBy) {
sortBy = 'id';
}
const count = await this.prisma.bot.count({ where: filterQuery });
const data = await this.prisma.bot.findMany({
skip: perPage * (page - 1),
take: perPage,
where: filterQuery,
include: this.include,
orderBy: {
[sortBy]: 'asc'
}
});
this.logger.log(`BotService::find: Returning response of find query. Time taken: ${performance.now() - startTime} milliseconds.`);
return { data: data, totalCount: count };
}

async findForAdmin(
perPage: number,
page: number,
name: string,
startingMessage: string,
match: boolean,
ownerID: string,
ownerOrgID: string,
): Promise<Bot[] | null> {
let filterQuery: any = {
ownerID: ownerID,
ownerOrgID: ownerOrgID,
OR: [
{
name: match ? name : caseInsensitiveQueryBuilder(name),
},
{
startingMessage: match
? startingMessage
: caseInsensitiveQueryBuilder(startingMessage),
},
],
};
return this.prisma.bot.findMany({
skip: perPage * (page - 1),
take: perPage,
where: filterQuery,
include: this.include,
});
return { data: data, totalCount: data.length };
}

async update(id: string, updateBotDto: any) {
Expand Down

0 comments on commit eb4377d

Please sign in to comment.