Created
April 5, 2018 08:39
-
-
Save n3tr/2b01c27b676ee4cab4fcbe02f2a36313 to your computer and use it in GitHub Desktop.
Create Sequelize Model Facebook DataLoader
This file contains hidden or 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
const _ = require('lodash') | |
const { Op } = require('sequelize') | |
const DataLoader = require('dataloader') | |
// eslint-disable-next-line | |
const createModelLoader = (Model, inField) => { | |
return new DataLoader(async (keys) => { | |
// Create id:index map for further use | |
const idIndexMap = keys.reduce((map, key, index) => { | |
map[key] = index | |
return map | |
}, {}) | |
// Query all models in keys | |
const models = await Model.findAll({ | |
where: { [inField]: { [Op.in]: keys } } | |
}) | |
// create empty array size match keys size | |
const result = Array.from(keys).fill(undefined) | |
// map user to match key index | |
_.forEach(models, (model) => { | |
const index = idIndexMap[model[inField]] | |
result[index] = model | |
}) | |
return result | |
}) | |
} | |
module.exports = { | |
createModelLoader | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment