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
122 stars 12 forks source link

How do you specify a required parameter that gets automatically initialized in Typescript? #74

Open Ansis100 opened 1 year ago

Ansis100 commented 1 year ago

Using the Typescript method of defining models, you can define a model's properties such as:

type UserPropertiesI = {
  uuid: string;
  username: string;
}

And initialize a field automatically using beforeCreate:

User.beforeCreate = (instance: UserInstance) => {
  instance.uuid = uuidv4();
};

This works fine. You can even set required: true in the schema for uuid and the model will still be valid.

However, the problem occurs when using, for example, createOne. The method expects an object of type UserPropertiesI as an argument, which means that uuid is a required field. We don't want to pass the UUID as an argument, we want to use the UUID Neogma generates for us.

We could set the UUID as optional with uuid?: string;. This means that createOne does not need uuid to be set, but it will still automatically initialize it. That creates another issue - Typescript now thinks that UUID can be undefined even though we initialize it every time a model gets created.

How do we specify that uuid is not required to create a model and that it is always defined?

themetalfleece commented 1 year ago

Hey! Right now this isn't possible. Other ORMs support this by providing different types on the model definition (one for the properties on creation, and one for those on fetch). This is something that'll be a nice improvement. Until then you'll need to do a workaround, like setting uuid: '' when calling createOne 🤔