Pagination
1. Offset pagination
Tham số đầu vào
OffsetPagination.PagingArgs<T>
Giá trị trả về
OffsetPagination.Responses<T>
Ví dụ
Filename app/infrastructure/models/todo/model.ts
// Your code
...
// Add offsetPaging plugin to schema
TodoSchema.plugin(offsetPaging);
interface Statics extends Model<TodoEntity.Todo> {
offsetPaginate(args: OffsetPagination.PagingArgs<TodoEntity.Todo>): Promise<OffsetPagination.Response<TodoEntity.Todo>>;
}
export const TodoModel = mongooseInstance.model<TodoDocument, Statics>(DOCUMENT_NAME, TodoSchema);
Filename app/infrastructure/models/todo/repository.ts
...
const createTodoRepository = (): TodoRepository => ({
...,
listByPagination: async ({ q, limit, page, sort }) => {
const listPagination = await TodoModel.offsetPaginate({
queries: { limit, page, sort },
pipelines: [
{
$match: {
$or: [{ title: { $regex: q, $options: 'i' } }, { description: { $regex: q, $options: 'i' } }],
},
},
],
});
return listPagination;
},
...
});
export const todoRepository = createTodoRepository();
Interface
export namespace OffsetPagination {
export interface Queries {
q?: string;
sort?: string;
page: number;
limit: number;
}
export interface Response<T> {
data: T[];
totalPage: number;
currentPage: number;
}
export interface PagingArgs<T> {
queries?: Omit<Queries, 'q'>;
pipelines?: PipelineStage[];
select?: { [P in keyof Partial<T>]: number } | Array<keyof T>;
}
}
2. Cursor pagination
Tham số đầu vào
CursorPagination.PagingArgs<T>
Giá trị trả về
CursorPagination.Responses<T>
Ví dụ
Filename app/infrastructure/models/todo/model.ts
// Your code
...
// Add cursorPaging plugin to schema
TodoSchema.plugin(cursorPaging);
interface Statics extends Model<TodoEntity.Todo> {
cursorPaginate(args: CursorPagination.PagingArgs<TodoEntity.Todo>): Promise<CursorPagination.Response<TodoEntity.Todo>>;
}
export const TodoModel = mongooseInstance.model<TodoDocument, Statics>(DOCUMENT_NAME, TodoSchema);
Filename app/infrastructure/models/todo/repository.ts
...
const createTodoRepository = (): TodoRepository => ({
...,
listByCursorPagination: async ({ q, limit, nextCursor, previousCursor, sort }) => {
const listPagination = await TodoModel.cursorPaginate({
queries: { limit, nextCursor, previousCursor, sort },
pipelines: [
{
$match: {
$or: [{ title: { $regex: q, $options: 'i' } }, { description: { $regex: q, $options: 'i' } }],
},
},
],
});
return listPagination;
},
...
});
export const todoRepository = createTodoRepository();
Interface
export namespace CursorPagination {
export interface Queries {
q?: string;
sort?: string;
limit?: number;
nextCursor: string | null;
previousCursor: string | null;
}
export interface Response<T> {
data: T[];
nextCursor: string | null;
previousCursor: string | null;
}
export interface PagingArgs<T> {
queries?: Omit<Queries, 'q'>;
pipelines?: PipelineStage[];
select?: { [P in keyof Partial<T>]: number } | Array<keyof T>;
}
}
Ghi chú
- Để chuyển đổi
shopify pagination
sangcursor pagination
dùng PaginationDTO