2019-05-08 15:45:37 +00:00
|
|
|
// Copyright IBM Corp. 2016,2018. All Rights Reserved.
|
|
|
|
// Node module: loopback-datasource-juggler
|
|
|
|
// This file is licensed under the MIT License.
|
|
|
|
// License text available at https://opensource.org/licenses/MIT
|
|
|
|
|
2016-08-15 12:55:26 +00:00
|
|
|
'use strict';
|
|
|
|
|
2018-12-07 14:54:29 +00:00
|
|
|
const asyncIterators = require('async-iterators');
|
|
|
|
const bdd = require('../helpers/bdd-if');
|
|
|
|
const helpers = require('./_helpers');
|
|
|
|
const should = require('should');
|
2016-08-15 12:55:26 +00:00
|
|
|
|
|
|
|
module.exports = function(dataSourceFactory, connectorCapabilities) {
|
2018-12-07 14:54:29 +00:00
|
|
|
const canIterateKeys = connectorCapabilities.canIterateKeys !== false;
|
2016-10-07 14:26:18 +00:00
|
|
|
|
|
|
|
bdd.describeIf(canIterateKeys, 'iterateKeys', function() {
|
2018-12-07 14:54:29 +00:00
|
|
|
let CacheItem;
|
2017-01-10 08:18:04 +00:00
|
|
|
beforeEach(setupCacheItem);
|
2016-08-15 12:55:26 +00:00
|
|
|
|
|
|
|
it('returns AsyncIterator covering all keys', function() {
|
|
|
|
return helpers.givenKeys(CacheItem, ['key1', 'key2'])
|
|
|
|
.then(function() {
|
2018-12-07 14:54:29 +00:00
|
|
|
const it = CacheItem.iterateKeys();
|
2016-08-15 12:55:26 +00:00
|
|
|
should(it).have.property('next');
|
|
|
|
return toArray(it);
|
|
|
|
})
|
|
|
|
.then(function(keys) {
|
|
|
|
keys.sort();
|
|
|
|
should(keys).eql(['key1', 'key2']);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
it('returns AsyncIterator supporting Promises', function() {
|
2018-12-07 14:54:29 +00:00
|
|
|
let iterator;
|
2016-08-15 12:55:26 +00:00
|
|
|
return helpers.givenKeys(CacheItem, ['key'])
|
|
|
|
.then(function() {
|
|
|
|
iterator = CacheItem.iterateKeys();
|
|
|
|
return iterator.next();
|
|
|
|
})
|
|
|
|
.then(function(key) {
|
|
|
|
should(key).equal('key');
|
|
|
|
return iterator.next();
|
|
|
|
})
|
|
|
|
.then(function(key) {
|
|
|
|
// Note: AsyncIterator contract requires `undefined` to signal
|
|
|
|
// the end of the sequence. Other false-y values like `null`
|
|
|
|
// don't work.
|
|
|
|
should(key).equal(undefined);
|
|
|
|
});
|
|
|
|
});
|
2017-01-10 08:18:04 +00:00
|
|
|
|
|
|
|
function setupCacheItem() {
|
|
|
|
return helpers.givenCacheItem(dataSourceFactory)
|
|
|
|
.then(ModelCtor => CacheItem = ModelCtor);
|
2018-12-07 14:43:40 +00:00
|
|
|
}
|
2016-08-15 12:55:26 +00:00
|
|
|
});
|
|
|
|
};
|
2018-10-05 07:30:02 +00:00
|
|
|
|
|
|
|
// A promisified version of asyncIterators.toArray
|
|
|
|
// Node.js 8.x does not have util.promisify function,
|
|
|
|
// we are adding promise support manually here
|
|
|
|
function toArray(iter) {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
asyncIterators.toArray(iter, (err, result) => {
|
|
|
|
if (err) reject(err);
|
|
|
|
else resolve(result);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|