diff --git a/packages/database-ql/src/interface.ts b/packages/database-ql/src/interface.ts index d0949818c2..011375380b 100644 --- a/packages/database-ql/src/interface.ts +++ b/packages/database-ql/src/interface.ts @@ -38,6 +38,7 @@ export interface QueryParam { offset?: number limit?: number projection?: ProjectionType + count?: boolean /** * Update options diff --git a/packages/database-ql/src/query.ts b/packages/database-ql/src/query.ts index 8540317dc0..49cbbf60cc 100644 --- a/packages/database-ql/src/query.ts +++ b/packages/database-ql/src/query.ts @@ -13,12 +13,25 @@ import { serialize } from './serializer/datatype' interface QueryOption { - // 查询数量 + /** + * 查询数量 + */ limit?: number - // 偏移量 + + /** + * 偏移量 + */ offset?: number - // 指定显示或者不显示哪些字段 + + /** + * 指定显示或者不显示哪些字段 + */ projection?: ProjectionType + + /** + * 是否返回文档总数 + */ + count?: boolean } @@ -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 } /** @@ -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 } diff --git a/packages/database-ql/tests/units/get/field.js b/packages/database-ql/tests/units/get/field.test.js similarity index 100% rename from packages/database-ql/tests/units/get/field.js rename to packages/database-ql/tests/units/get/field.test.js diff --git a/packages/database-ql/tests/units/get/page.test.js b/packages/database-ql/tests/units/get/page.test.js new file mode 100644 index 0000000000..34683b1f34 --- /dev/null +++ b/packages/database-ql/tests/units/get/page.test.js @@ -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) + }) + }) \ No newline at end of file