`validate` should not be called when attribute is not required and null/undefined
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
validateproperty: https://electrodb.dev/en/modeling/attributes/#validate - This page speaks of a
validationproperty (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.
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),
}
@solaris007,
I think this is what I was seeing here: https://github.com/tywalch/electrodb/discussions/432#discussioncomment-11130684