Last active
August 10, 2017 02:57
-
-
Save skinofstars/be836762627ce26b8c8505d6c09df25c to your computer and use it in GitHub Desktop.
Feathers hook for including seqeulize models
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'; | |
// Feathers hook to do `/thing?includes=other` | |
// before : { | |
// find: [modelIncludes()], | |
// get: [modelIncludes()] | |
// }, | |
// after : { | |
// find: [modelIncludes()], | |
// get: [modelIncludes()] | |
// } | |
// This is an efficient way to include associations using sequelize. | |
// Shame sequelize has a bug that means its findAndCount doesn't include a | |
// count once `raw:false` is included, which we need to get 1:m array. | |
// https://github.com/sequelize/sequelize/issues/7931 | |
// Ensure you also include this both before to set up the include, | |
// and after to reset the count. | |
module.exports = () => { | |
return hook => { | |
if (hook.type === 'before') { | |
let includes; | |
if (hook.params.query.includes) { | |
includes = hook.params.query.includes; | |
hook.params.includes = includes; | |
delete hook.params.query.includes; | |
if (!Array.isArray(includes)) includes = [includes]; | |
let models = includes | |
.filter(include => hook.app.services[include]) | |
.map(include => | |
hook.app.services[include].Model.schema( | |
hook.params.agencyConfig.pg_schema | |
) | |
); | |
if (!hook.params.sequelize) hook.params.sequelize = {}; | |
Object.assign(hook.params.sequelize, { | |
raw: false, | |
include: models | |
}); | |
} | |
} | |
// | |
if (hook.type === 'after' && hook.method === 'find') { | |
if (hook.params.includes) { | |
return hook.service.Model.count().then(count => { | |
hook.result.total = count; | |
return hook; | |
}); | |
} | |
} | |
return hook; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment