Last active
April 23, 2019 08:31
-
-
Save motephyr/23704da41ba8d7b60e51bfcf959a6da2 to your computer and use it in GitHub Desktop.
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 DataLoader = require('dataloader') | |
/** | |
* Creates a dataloader for a supplied model. | |
* | |
* @param {String} model e.g. 'App/Models/User' | |
* @param {String} ref_id e.g. 'order_id' | |
* @returns {DataLoader} | |
*/ | |
function createLoader(model, ref_id = 'id', has = 'one') { | |
let batchLoadFn = async (keys) => { | |
let data = await queryData(model, ref_id, keys) | |
return sortData(data.rows, ref_id, keys, has) | |
} | |
return new DataLoader(batchLoadFn) | |
} | |
// 這裡是adonis.js的query範例. | |
// 可以將queryData的內容抽換成你query db的方式。 | |
async function queryData(model, ref_id, keys) { | |
let Model = use(model) | |
console.log(`*** loading all '${model}' with ids [${keys}] from database`) | |
return await Model | |
.query() | |
.whereIn(ref_id, keys) | |
.fetch() | |
} | |
function sortData(data, ref_id, keys, has) { | |
if (has === 'one') { | |
return keys.map(id => data.find(r => r[ref_id] === id)) | |
} else { | |
return keys.map(id => data.filter(r => r[ref_id] === id)) | |
} | |
} | |
module.exports = createLoader |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment