electrodb icon indicating copy to clipboard operation
electrodb copied to clipboard

`validate` should not be called when attribute is not required and null/undefined

Open solaris007 opened this issue 1 year ago • 2 comments

Describe the bug When an attribute is declared as not required and specifies a validate property, e.g.:

    someAttribute: {
      type: 'any',
      required: false,
      validate: (value) => !value || isNonEmptyObject(value),
    },

... the validation will be called, even if the attribute value is null/undefined, forcing a check to be added to the validation. This seems counter-intuitive and makes the schema validation settings more complex.

As a side note, there seems to be a documentation mismatch:

  • Use validate property: https://electrodb.dev/en/modeling/attributes/#validate
  • This page speaks of a validation property (which is never called, verified with debugger): https://electrodb.dev/en/modeling/attributes/#attribute-validation

ElectroDB Version 3.0.1

Expected behavior If an attribute has the required property set to false, validation should not be called when the value is null or undefined.

solaris007 avatar Nov 26 '24 04:11 solaris007

The validate fn is ultimately the gatekeeper of the column and is there to ensure that any value set to that column is allowed. The only time the function would called without the user supplying a value is during a create, put, or upsert operation, where all values are validated (even undefined ones) to ensure the state of each column is valid.

If you would like that value to never arrive undefined but also not have it be required, you could use a default:

someAttribute: {
  type: 'any',
  
  // you could set this `true` here when `default` is used; having a default will change the typing of this attribute to optional
  required: false,
  
  // default: () => ({ someInitialKey: "someInitialValue" }) <-- can also be a function
  default: { someInitialKey: "someInitialValue" },
  
  // validate will receive the default, and only be invoked with user-applied values for the rest of the item's life cycle
  validate: (value) => isNonEmptyObject(value),
}

tywalch avatar Nov 27 '24 14:11 tywalch

@solaris007,

I think this is what I was seeing here: https://github.com/tywalch/electrodb/discussions/432#discussioncomment-11130684

dls314 avatar Jan 03 '25 21:01 dls314