themetalfleece / neogma

Object-Graph-Mapping neo4j framework, Fully-typed with TypeScript, for easy and flexible node and relationship operations
https://themetalfleece.github.io/neogma/
MIT License
124 stars 12 forks source link

primary key generation with 'before create' like hook #9

Closed tejo-ak closed 3 years ago

tejo-ak commented 3 years ago

I want to manage id generation across different Models consistently. Is it possible to add a new hook right before a record is saved to the database?

Thanks.

themetalfleece commented 3 years ago

This does sound useful. I'll get to it soon

themetalfleece commented 3 years ago

Published in 1.7.0, docs can be found here. Let me know if there is anything that's missing.

tejo-ak commented 3 years ago

Perfect! Thanks a lot for considering the suggestion and implementing it.

tejo-ak commented 3 years ago

Hello, I tested the new version with the hook. It works like a charm. I noticed that you put the hook after schema validation. Since the hook can change the data after being validated, the validation is too early and may not be very useful. Also, one of the purposes of using the hook was to set a primary key (id). Therefore my data which has no id when initialized failed the validation. (I have to set my id 'required' false).

themetalfleece commented 3 years ago

That makes sense. Do you think that beforeCreate should run before the validation, or should a new hook beforeValidate be added? Like with sequelize hooks, where beforeValidate runs, then the instance is validated, and then beforeCreate runs.

tejo-ak commented 3 years ago

It works for me.

Making the Sequelize as a reference is a good move.

themetalfleece commented 3 years ago

Thanks for your input. I tested beforeValidate/afterValidate hooks, and wasn't happy with the result. It added complexity, while making some things unclear. Also, I'm not in favor of mutating data in the beforeValidate hook. Therefore, I implemented the original concept of beforeCreate running before validating the instance.

Published in 1.8.1.

This solution should solve your issue, let me know if anything doesn't go as planned!