Skip to content

Instantly share code, notes, and snippets.

@sicruse
Created May 15, 2017 22:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sicruse/bfaa17008990bab2fd1d76a670c3923f to your computer and use it in GitHub Desktop.
Save sicruse/bfaa17008990bab2fd1d76a670c3923f to your computer and use it in GitHub Desktop.
Example use of feathers-sequelize object hydration
const hydrate = require('feathers-sequelize/hooks/hydrate');
function includePoster() {
return function (hook) {
const model = hook.app.service('users').Model;
const association = { include: [{ model: model, as: 'poster', attributes: ['userId', 'displayName', 'avatar'] }] };
switch (hook.type) {
case 'before':
hook.params.sequelize = Object.assign(association, { raw: false });
return Promise.resolve(hook);
break;
case 'after':
hydrate( association ).call(this, hook);
break;
}
}
}
module.exports = {
before: {
all: [ includePoster() ],
...
},
after: {
all: [ includePoster() ],
...
},
error {
...
}
};
@matb33
Copy link

matb33 commented Jun 29, 2017

Isn't hydrate in the after hook redundant by having { raw: false } in the before hook? Or did you perhaps mean to dehydrate in the after hook instead?

@mauchiyuyo
Copy link

mauchiyuyo commented Aug 27, 2017

hello, I have used your code and it works nice but I have a question.
I have a Model that has many hasMany models like this:
Model1 hasMany Model2
Model1 hasMany Model3
Model1 hasMany Model4
Model3 hasMany Model4
Model1 hasMany Model5

So, when I add multiple hooks it only includes the last hook included.

My question, how do I choose only one of the hasMany models associated to Model1? And how do I include the cascade models like Model3 has?
And, of course, how to query/filtrate the associated included to only select the desired records?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment