Roy
Roy

Reputation: 1518

How do I run a callback function after a SailsJS REST Blueprint?

Is there a best practice for a callback after a blueprint route in SailsJS 11.x?

I have an API where Users can submit Ideas. After the Idea is created, if it's the User's first Idea they should get a Badge. As far as I can tell there are two places to put this functionality.

  1. Copy/Override the Sails rest blueprint, add the functionality to the Idea.create() callback function.
  2. Add a lifecycle callback for the afterCreate action on the Idea model.

I'm assuming any functionality I write in terms of granting badges should be put in a Service so it can be shared among the different models. It seems like option 1 wouldn't be as tightly coupled, but would lead to fatter controllers.

Upvotes: 1

Views: 373

Answers (2)

Dinana
Dinana

Reputation: 300

I would go for the second option, however you should note that afterCreate gets triggered when testing via barrels and adding items, which might be an issue for the logic in afterCreate. (Ex: A user has 3 ideas, 1 badge from the first idea, you add them to barrels fixtures. When barrels is adding the first idea it will trigger the afterCreate then it will add the badge from the fixture resulting in the user having 2 duplicate badges.)

Upvotes: 1

sgress454
sgress454

Reputation: 24958

Overriding the "create" blueprint will mean that every model will use that code when handling a request to their POST /<modelName> route, which is probably not what you want. The lifecycle callback will work fine for granting the badge, but if you're looking to modify the response based on whether or not a badge was granted, this approach won't work--but you could easily send a socket notification from the lifecycle callback, using User.message().

The third option is just to override the create action in IdeaController.js. There's not all that much to it, especially if you let Waterline handle most of the field validation for you. In essence, it's just:

create: function(req, res) {
  Idea.create(req.params.all()).exec(function(err, idea) {
     if (err) {return res.negotiate(err);}
     // ... do some stuff with the idea and send a response ...
  });
}

Upvotes: 2

Related Questions