Skip to content

Commit

Permalink
fix(cache): Support nsql-cache 1.1.3
Browse files Browse the repository at this point in the history
  • Loading branch information
sebelga committed Aug 18, 2018
1 parent 0a0838d commit 31d9767
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 9 deletions.
21 changes: 14 additions & 7 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ class Model extends Entity {
options = args.length > 4 ? args[4] : {};

const key = this.key(ids, ancestors, namespace);
const isMultiple = Array.isArray(id) && key.length > 1;

/**
* If gstore has been initialize with a cache we first fetch
Expand All @@ -166,7 +167,17 @@ class Model extends Entity {
if (this.__hasCache(options)) {
const fetchHandler = keys => fetchEntity(keys);
return this.gstore.cache.keys.read(key, options, fetchHandler)
.then(res => [res]) // google-cloud returns entity(ies) in response[0]
.then((res) => {
if (!Array.isArray(res) || (isMultiple && res.length !== 1)) {
/*
* google-cloud returns entity(ies) in response[0]
* So we make sure that the response from the cache
* has the same interface
*/
return [res];
}
return res;
})
.then(onEntity)
.catch(onError);
}
Expand All @@ -179,7 +190,6 @@ class Model extends Entity {

function fetchEntity(keys = key) {
keys = arrify(keys);
const isMultiple = keys.length > 1;
const { dataloader } = options;

if (transaction) {
Expand All @@ -194,11 +204,9 @@ class Model extends Entity {
return cb(new GstoreError(errorCodes.ERR_GENERIC, 'dataloader must be a "DataLoader" instance'));
}
if (isMultiple) {
return dataloader.loadMany(keys)
.then(e => [e]); // google-cloud returns entity(ies) in response[0];
return dataloader.loadMany(keys);
}
return dataloader.load(keys[0])
.then(e => [e]);
return dataloader.load(keys[0]);
}
keys = isMultiple ? keys : keys[0];
return _this.gstore.ds.get(keys);
Expand All @@ -215,7 +223,6 @@ class Model extends Entity {
}

let entity = arrify(data[0]).filter(_entity => typeof _entity !== 'undefined');
const isMultiple = ids.length > 1;

entity = entity.map(_entity => _this.__model(_entity, null, null, null, _entity[_this.gstore.ds.KEY]));

Expand Down
3 changes: 1 addition & 2 deletions test/model-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -508,8 +508,7 @@ describe('Model', () => {
.then((response) => {
assert.ok(ds.get.called);
const { args } = ds.get.getCall(0);
assert.ok(!Array.isArray(args[0]));
expect(args[0].id).equal(123);
expect(args[0][0].id).equal(123);
expect(response.length).equal(2);
})
));
Expand Down

0 comments on commit 31d9767

Please sign in to comment.