Meteor-Community-Packages / meteor-collection-hooks

Meteor Collection Hooks
https://atmospherejs.com/matb33/collection-hooks
MIT License
656 stars 90 forks source link

Throw in before.* should also cancel the operation #310

Open KoenLav opened 4 months ago

KoenLav commented 4 months ago

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!

github-actions[bot] commented 4 months ago

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.

Roshdy commented 2 months ago

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.