feat: add order to pagination

This commit is contained in:
Chen, Tai-Lin committed 2023-12-21 17:28:48 +08:00
1 parent 68db16419d
commit fa36b63fbe
8 files changed
+85 -50

No files matched your search

+2 -2
View File
@@ -3,7 +3,7 @@ import { Command } from '@linux-odyssey/models'
// eslint-disable-next-line import/prefer-default-export
export async function errorCommands(pagination) {
const commands = await Command.aggregate([
pagination.matchStage('_id'),
pagination.match('_id'),
{
$match: {
$and: [
@@ -31,7 +31,7 @@ export async function errorCommands(pagination) {
},
},
{ $unwind: '$session.user' },
pagination.order('_id'),
pagination.sort('_id'),
pagination.limit(),
])
+44 -24
View File
@@ -3,40 +3,60 @@
// eslint-disable-next-line max-classes-per-file
import mongoose from 'mongoose'
class Pagination {
export const DESC = 'desc'
export const ASC = 'asc'
class Asc {
getOperator() {
return '$gt'
}
getOrder() {
return 1
}
}
class Desc {
getOperator() {
return '$lt'
}
getOrder() {
return -1
}
}
export default class Pagination {
nextKey = null
itemsPerPage = 50
order = null
constructor(itemsPerPage = 50, nextKey = null) {
constructor(order, itemsPerPage = 50, nextKey = null) {
this.itemsPerPage = itemsPerPage
if (!order || order === DESC) {
this.order = new Desc()
} else if (order === ASC) {
this.order = new Asc()
} else {
throw new Error('order must be asc or desc')
}
if (nextKey) {
this.nextKey = new mongoose.Types.ObjectId(nextKey)
}
}
match(field) {
const stage = this.nextKey
? { [field]: { [this.order.getOperator()]: this.nextKey } }
: {}
return { $match: stage }
}
sort(field) {
return { $sort: { [field]: this.order.getOrder() } }
}
limit() {
return { $limit: this.itemsPerPage }
}
}
export class Asc extends Pagination {
matchStage(field) {
const stage = this.nextKey ? { [field]: { $gt: this.nextKey } } : {}
return { $match: stage }
}
order(field) {
return { $sort: { [field]: 1 } }
}
}
export class Desc extends Pagination {
matchStage(field) {
const stage = this.nextKey ? { [field]: { $lt: this.nextKey } } : {}
return { $match: stage }
}
order(field) {
return { $sort: { [field]: -1 } }
}
}
+2 -2
View File
@@ -32,7 +32,7 @@ function formatTime(time) {
export async function sessionList(pagination) {
const sessions = await Session.aggregate([
pagination.matchStage('_id'),
pagination.match('_id'),
{
$lookup: {
from: 'users',
@@ -50,7 +50,7 @@ export async function sessionList(pagination) {
as: 'commands',
},
},
pagination.order('_id'),
pagination.sort('_id'),
pagination.limit(),
])
+2 -2
View File
@@ -14,7 +14,7 @@ export function userCount() {
export async function userList(pagination) {
const users = await Session.aggregate([
pagination.matchStage('user'),
pagination.match('user'),
{
$group: {
_id: '$user',
@@ -31,7 +31,7 @@ export async function userList(pagination) {
},
},
{ $unwind: '$userData' },
pagination.order('userData._id'),
pagination.sort('userData._id'),
pagination.limit(),
])