diff --git a/index.js b/index.js index 1e7208a..13df456 100644 --- a/index.js +++ b/index.js @@ -302,11 +302,14 @@ class Squeakquel extends Datastore { /** * Scan records in the datastore * @method scan - * @param {Object} config Configuration object - * @param {String} config.table Table name - * @param {Object} [config.params] index => values to query on - * @param {String} [config.sort] Sorting option based on GSI range key. Ascending or descending. - * @return {Promise} Resolves to an array of records + * @param {Object} config Configuration object + * @param {String} config.table Table name + * @param {Object} [config.paginate] Pagination parameters + * @param {Number} [config.paginate.count] Number of items per page + * @param {Number} [config.paginate.page] Specific page of the set to return + * @param {Object} [config.params] index => values to query on + * @param {String} [config.sort] Sorting option based on GSI range key. Ascending or descending. + * @return {Promise} Resolves to an array of records */ _scan(config) { const table = this.tables[config.table]; @@ -320,6 +323,11 @@ class Squeakquel extends Datastore { return Promise.reject(new Error(`Invalid table name "${config.table}"`)); } + if (config.paginate) { + findParams.limit = config.paginate.count; + findParams.offset = findParams.limit * (config.paginate.page - 1); + } + if (config.params && Object.keys(config.params).length > 0) { Object.keys(config.params).forEach((paramName) => { const paramValue = config.params[paramName]; diff --git a/package.json b/package.json index bc17c99..2d1d680 100644 --- a/package.json +++ b/package.json @@ -41,6 +41,7 @@ "chai": "^4.0.2", "eslint": "^3.19.0", "eslint-config-screwdriver": "^2.1.3", + "eslint-plugin-import": "^2.9.0", "jenkins-mocha": "^4.1.2", "joi": "^10.5.2", "mockery": "^2.0.0", diff --git a/test/index.test.js b/test/index.test.js index 337cc9e..85dde3f 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -560,6 +560,39 @@ describe('index test', function () { }); }); + it('scans a page of data', () => { + const dummyData = []; + + for (let i = 1; i <= 30; i += 1) { + dummyData.push({ + id: `data${i}`, + key: `value${i}` + }); + } + + const testData = dummyData.slice(11, 21); + const testInternal = testData.map(data => ({ + toJSON: sinon.stub().returns(data) + })); + + testParams.paginate = { + count: 10, + page: 2 + }; + + sequelizeTableMock.findAll.resolves(testInternal); + + return datastore.scan(testParams).then((data) => { + assert.deepEqual(data, testData); + assert.calledWith(sequelizeTableMock.findAll, { + where: {}, + order: [['id', 'DESC']], + limit: 10, + offset: 10 + }); + }); + }); + it('scans for some data with params', () => { const testData = [ {