Skip to content

Instantly share code, notes, and snippets.

@skinofstars
Last active August 10, 2017 02:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skinofstars/be836762627ce26b8c8505d6c09df25c to your computer and use it in GitHub Desktop.
Save skinofstars/be836762627ce26b8c8505d6c09df25c to your computer and use it in GitHub Desktop.
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