1

We are in the process of building a cart with the loopback API.

When adding a product (ie. 12345) to a persistent database, I am checking to see if that item already exists in my "cart". If the item exists, I am incrementing the Quantity of that item. BUT, after incrementing I need to stop the item from being added to the cart.

In the "before save" operation hook, can I cancel the item from being added to the database. I need to be able to stop the save operation.

2

2 Answers 2

3

You should use findOrCreate() like @amuramoto suggests. But to answer your question, to cancel the save, call next() with an error:

next(err);

next(new Error('Why this is cancelled...'));

It's bad practice to call a save method inside a before save hook on the same model. Infinite looping can result very easily.

4
  • Thank You! FindOrCreate() is a great feature that I did not know about, but it didn't work for us here. I ended up moving the logic to the client side in our app with an extra ajax call to check for item present, if so, I call the update endpoint, else call the insert endpoint. I really wanted this in the loopback API, but just couldn't get it to work. We have a situation where we need to keep 2 different datasources in sync with the cart and it ended up getting too complicated. Mar 31, 2016 at 1:31
  • Any idea how to cancel the save but return success? I would like to have an API expose one model, but on POST of the model, do a conversion to another model and save that instead.
    – JBCP
    May 9, 2016 at 17:41
  • @JBCP That's not really great API design, especially for the next person who comes along to modify the code. Why not create a custom remote method on the first model and handle it manually, something like model.createWithFallback()? The logic really isn't suited for beforeSave trickery because you are already in the context of a save operation. You want a wrapper for either model's save, which says custom remote method to me.
    – notbrain
    May 9, 2016 at 18:44
  • @Brian - The goal was to have a model that takes a batch of another models - then on the client side save the individual model instances, rather than the outer batch. For example: "Batch embedsMany Eaches" -> POST Batch -> Save Eaches. This gives an atomic POST for multiple instances of Eaches.
    – JBCP
    May 10, 2016 at 2:32
1

Try the findOrCreate operation hook instead. It will look for an existing model based on a filter and create a new model if it isn't found.

https://apidocs.strongloop.com/loopback/#persistedmodel-findorcreate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.