Skip to content

Commit

Permalink
feat(db-ql): add page & count options for query
Browse files Browse the repository at this point in the history
  • Loading branch information
maslow committed Oct 19, 2021
1 parent e7545ca commit 1ecc32d
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 7 deletions.
1 change: 1 addition & 0 deletions packages/database-ql/src/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export interface QueryParam {
offset?: number
limit?: number
projection?: ProjectionType
count?: boolean

/**
* Update options
Expand Down
37 changes: 30 additions & 7 deletions packages/database-ql/src/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,25 @@ import { serialize } from './serializer/datatype'


interface QueryOption {
// 查询数量
/**
* 查询数量
*/
limit?: number
// 偏移量

/**
* 偏移量
*/
offset?: number
// 指定显示或者不显示哪些字段

/**
* 指定显示或者不显示哪些字段
*/
projection?: ProjectionType

/**
* 是否返回文档总数
*/
count?: boolean
}


Expand Down Expand Up @@ -270,10 +283,17 @@ export class Query {
* 设置分页查询
* @param options { current: number, size: number} `current` 是页码,默认为 `1`, `size` 是每页大小, 默认为 10
*/
public page(options: { current: number, size: number } = { current: 1, size: 10 }) {
const current = options.current || 1
const size = options.size || 10
return this.skip((current - 1) * size).limit(size)
public page(options: { current: number, size: number }) {
const current = options?.current || 1
const size = options?.size || 10

const query = this
.skip((current - 1) * size)
.limit(size)

query._queryOptions.count = true

return query
}

/**
Expand Down Expand Up @@ -464,6 +484,9 @@ export class Query {
if (this._queryOptions.projection) {
param.projection = this._queryOptions.projection
}
if (this._queryOptions.count) {
param.count = this._queryOptions.count
}

return param
}
Expand Down
27 changes: 27 additions & 0 deletions packages/database-ql/tests/units/get/page.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const { getDb } = require('../_utils')
const assert = require('assert')

describe('db::page()', () => {
it('page() should be ok', async () => {
const { db, req } = getDb()
const res = await db.collection('tasks')
.page()
.get()

console.log(req.params)
assert.equal(req.params.limit, 10)
assert.equal(req.params.count, true)
})

it('page({ current: 2, size: 10}) should be ok', async () => {
const { db, req } = getDb()
const res = await db.collection('tasks')
.page({ current: 3, size: 20 })
.get()

console.log(req.params)
assert.equal(req.params.offset, 40)
assert.equal(req.params.limit, 20)
assert.equal(req.params.count, true)
})
})

0 comments on commit 1ecc32d

Please sign in to comment.