meteor-collection-hooks icon indicating copy to clipboard operation
meteor-collection-hooks copied to clipboard

Throw in before.* should also cancel the operation

Open KoenLav opened this issue 1 year ago • 2 comments

Is your feature request related to a problem? Please describe. In a before.insert hook we are validating some data, and if not valid we want to show the user an error message by throwing an error AND cancel the operation.

Describe the solution you'd like I would like the operation to be stopped if a before.* hook throws.

Describe alternatives you've considered Not sure if we can fix this in any other way? Suggestions welcome!

KoenLav avatar Feb 28 '24 10:02 KoenLav

Thank you for submitting this issue!

We, the Members of Meteor Community Packages take every issue seriously. Our goal is to provide long-term lifecycles for packages and keep up with the newest changes in Meteor and the overall NodeJs/JavaScript ecosystem.

However, we contribute to these packages mostly in our free time. Therefore, we can't guarantee you issues to be solved within certain time.

If you think this issue is trivial to solve, don't hesitate to submit a pull request, too! We will accompany you in the process with reviews and hints on how to get development set up.

Please also consider sponsoring the maintainers of the package. If you don't know who is currently maintaining this package, just leave a comment and we'll let you know.

github-actions[bot] avatar Feb 28 '24 10:02 github-actions[bot]

The workaround for this is as follows.

// Schema Hook
schema.before.remove(function(userId, doc){
  let valid = false;
  // ...validation
  return valid;
})

If valid === false --> then the result of schema.remove() is 0 which can be treated as falsy value

So you can handle it in caller like this:

// Caller
const res = schema.remove({ _id: '...' });

if(!res){
  throw new Meteor.Error("Deletion is not allowed!!");
}

Of course that doesn't give room to handle multiple cases (i.e. different error messages). But should do the job for simple/singular cases.

Hope it helps.

Roshdy avatar May 15 '24 21:05 Roshdy