dchester / epilogue

Create flexible REST endpoints and controllers from Sequelize models in your Express app
846 stars 116 forks source link

Support sequelize options through context.sequelizeOptions #210

Open ArnaudD opened 7 years ago

ArnaudD commented 7 years ago

Hi,

We've been running with this fork for a year and though that this might interest someone.

We've added an attribute (sequelizeOptions) to epilogue context to specify options to sequelize find, create, update or destroy methods.

This is useful for enforcing attribute/model access control with sequelize hooks (with something that looks like ssacl-attribute-roles), or to easily dispatch "changes" somewhere else :

In epilogue resources declaration:

const passRequestToSequelize = {
  write: {
    before: function(request, response, context) {
      context.sequelizeOptions = {
        _request: request,
      };
      return context.continue;
    }
  }
};

export const changelog = {
  create: passRequestToSequelize,
  update: passRequestToSequelize,
  delete: passRequestToSequelize,
};

// ...

epilogueResource.use(changelog);

In sequelize initialization:

function customLog(type, instance, options) {
  const changes = instance.changed();
  logEvent({
    type: type,
    model: instance.Model,
    changes: changes ? changes.map(k => instance.previous(k)) : false,
    userId: options._request.currentUser.id
  })
}

const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname', config);

sequelize.addHook('afterCreate', customLog.bind(null, 'create'));
sequelize.addHook('afterUpdate', customLog.bind(null, 'update'));
sequelize.addHook('afterDestroy', customLog.bind(null, 'delete'));

What do you think ?

Thanks for epilogue !

Tmassery commented 6 years ago

So I was about to open the exact same PR, this would be a wonderful enhancement. Any chance this could get traction?

We need to pass in an auth token from the initial call handled by epilogue, down through to the sequelize hooks to make some external calls and notify other systems of the changes (using that same auth token)