Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Feathers hook for including seqeulize models
'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