Pass user object to model life cycle event in Sails.js

141 views Asked by At

I'm interested if anyone had managed to pass current logged in user to lifecycle events

I would like to pass the user to the lifecycle events function to keep track of the user making the changes.

1

There are 1 answers

5
arbuthnott On

I don't think there is a clean way to do this. Even if you don't mind digging into (and modifying) the framework code, I think you'd have to make a few modifications in a few places:

1 - You'd have to override Model.create to accept a req parameter (or something else you can use to get the logged in user).

2 - You'd have to make sure that all uses in the code (yours AND the sails library's) of Model.create pass in the required parameter. In particular...

3 - You'd have to modify the default action caught by POST /create/[modelname] so that it passed in the appropriate parameters to Model.create


Given that that is a lot of steps (and I likely missed some), I'd recommend another approach:

1 - Disable the REST create route from your /config/blueprints.js file.

2 - Funnel all model creation through a custom method. (Could be a directly exposed controller method, or something in /api/services, or in the model itself). Make sure the method gets access to the logged in user, attach it as data to the model, THEN call the default Model.create from within your custom method.