sails.js: Lifecycle callbacks for Models: Do they support beforeFind and afterFind?
Asked Answered
I

2

7

In sails.js, Models support lifecycle callbacks for validate, create, update and destroy.

Is there support for callbacks for find() or query as well? Like beforeFind() and afterFind()?

The idea is same. I would want to validate / modify parameters before the query is run or after the query is run.

Any thoughts?

Ibbie answered 27/1, 2015 at 10:5 Comment(1)
waterline does call beforeValidate() and afterValidate() for query as well. But we cannot differentiate in these callbacks, whether this is called for query or for create/update.Ibbie
D
4

As of writing this it does NOT support these requests, however their is a pull request https://github.com/balderdashy/waterline/pull/525

You can use policies to do this in the mean time.

Dug answered 27/1, 2015 at 23:17 Comment(1)
Thanks for the input. Policies will work, but I would like to cover those cases, where we call the ORM, from the controllers and other places within the server side. The pull request has one comment, that specifies how to achieve this req, albeit not the best way. At least, temporarily I will go ahead with that method (gist.github.com/mphasize/d62ad412e85bda06377c)Ibbie
K
1

i don't get why this was left out in the first place. It's actually logical to want to add some data to the fetched model data after each model find.

The closest thing to afterFind in the documentation as of writting is customToJson model setting.

customToJSON: function() { 
    // Return a shallow copy of this record with the password and ssn removed. 
    return _.omit(this, ['password', 'ssn']) 
}

you basically do your stuff before the return omit part. I still don't get why these lifecycles were omitted.

I think I am going to write a hook to provide these for now. I will post it here.

Kin answered 27/7, 2018 at 1:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.