Skip to content

Commit

Permalink
feat: add pagination for thread list api (#1000)
Browse files Browse the repository at this point in the history
  • Loading branch information
marknguyen1302 committed Aug 8, 2024
1 parent fcbf842 commit 5fee4a2
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,13 @@ export class ThreadsController {
'Lists all the available threads along with its configurations.',
})
@Get()
findAll() {
return this.threadsUsecases.findAll();
findAll(
@Query('limit', new DefaultValuePipe(20)) limit: number,
@Query('order', new DefaultValuePipe('desc')) order: 'asc' | 'desc',
@Query('after') after?: string,
@Query('before') before?: string,
) {
return this.threadsUsecases.findAll(limit, order, after, before);
}

@ApiOperation({
Expand Down
66 changes: 62 additions & 4 deletions cortex-js/src/usecases/threads/threads.usecases.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,69 @@ export class ThreadsUsecases {
return this.threadRepository.create(thread);
}

async findAll(): Promise<Thread[]> {
return this.threadRepository.findAll({
include: [{ all: true }],
order: [['created_at', 'DESC']],
async findAll(
limit: number,
order: 'asc' | 'desc',
after?: string,
before?: string,
): Promise<PageDto<Thread>> {
const normalizedOrder = order === 'asc' ? 'ASC' : 'DESC';
let afterQuery = {};
let beforeQuery = {};
if (after) {
const [afterDate, afterId] = after.split('_');
const operator = order === 'asc' ? Op.gt : Op.lt;
afterQuery = {
[Op.or]: [
{
created_at: { [operator]: Number(afterDate) },
},
{
created_at: Number(afterDate),
id: { [operator]: afterId },
},
],
};
}
if (before) {
const [beforeDate, beforeId] = before.split('_');
const operator = order === 'asc' ? Op.lt : Op.gt;
beforeQuery = {
[Op.or]: [
{
created_at: { [operator]: Number(beforeDate) },
},
{
created_at: Number(beforeDate),
id: { [operator]: beforeId },
},
],
};
}
const threads = await this.threadRepository.findAll({
order: [
['created_at', normalizedOrder],
['id', normalizedOrder],
],
limit: limit + 1,
where: {
[Op.and]: [afterQuery, beforeQuery],
},
});
let hasMore = false;
if (threads.length > limit) {
hasMore = true;
threads.pop();
}
const firstItem = threads[0];
const lastItem = threads[threads.length - 1];
const firstId = firstItem
? `${firstItem.created_at}_${firstItem.id}`
: undefined;
const lastId = lastItem
? `${lastItem?.created_at}_${lastItem?.id}`
: undefined;
return new PageDto(threads, hasMore, firstId, lastId);
}

async getMessagesOfThread(
Expand Down

0 comments on commit 5fee4a2

Please sign in to comment.