-
-
Save svnlto/54b70e41ec7823812665dc7f74f2e145 to your computer and use it in GitHub Desktop.
Use facebook's dataloader to batch any Service get
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const DataLoader = require('dataloader'); | |
class Service { | |
constructor({ BaseService, options }) { | |
this.id = BaseService.id || 'id'; | |
this.service = BaseService; | |
this.dataloader = new DataLoader(this._batchGet.bind(this), options); | |
} | |
_batchGet(ids) { | |
console.log('Batched Ids: ', ids.join(',')); | |
const cachedPromises = {}; | |
const promises = ids.map((id) => { | |
if (cachedPromises[id] === undefined) { | |
cachedPromises[id] = this.service.get(id); | |
} | |
return cachedPromises[id]; | |
}); | |
return Promise.all(promises); | |
} | |
find(params) { | |
return this.service.find(params) | |
.then((result) => { | |
if (Array.isArray(result)) { | |
result.forEach((object) => { | |
this.dataloader.prime(object[this.id], object); | |
}); | |
} | |
return result; | |
}); | |
} | |
get(id, params) { | |
return this.dataloader.load(id); | |
} | |
create(data, params) { | |
if(Array.isArray(data)) { | |
return Promise.all(data.map(current => this.create(current))); | |
} | |
return this.service.create(data, params) | |
.then((object) => { | |
this.dataloader.prime(object[this.id], object); | |
return object; | |
}); | |
} | |
update(id, data, params) { | |
return this.service.update(id, data, params) | |
.then((object) => { | |
this.dataloader.clear(id).prime(id, object); | |
return object; | |
}); | |
} | |
patch(id, data, params) { | |
return this.service.patch(id, data, params) | |
.then((object) => { | |
this.dataloader.clear(id).prime(id, object); | |
return object; | |
}); | |
} | |
remove(id, params) { | |
return this.service.remove(id, params) | |
.then((object) => { | |
this.dataloader.clear(id); | |
return object; | |
}); | |
} | |
} | |
function initService(options) { | |
return new Service(options); | |
} | |
module.exports = initService; | |
module.exports.Service = Service; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment