DataStore - Omitting an optional field from a model object results in error on save
See original GitHub issueDescribe the bug
Given a GraphQL schema which defines a model type with an optional (string) value, if a model instance is saved without defining that value (it’s optional after all), it will fail; definging a null
value for the optional value succeeds.
To Reproduce This was recently demonstrated to us when we had a graphql schema like the following:
type Movie @model {
id: ID!
name: String!
description: String
}
When calling something like:
await DataStore.save(
new Movie({
name: "Dumb and Dumber",
})
);
The local DataStore appears to be updated but I see the following error logged as a warning:
[WARN] 06:03.591 DataStore - failed to execute errorHandler, [Error: Field description should be of type string, undefined received. undefined]
Expected behavior
All optional fields should be able to be omitted when saved and it should succeed without populating that value. Alternatively, it can also be explicitly specified as undefined
or null
which is particularly useful on updates to clear out a field.
Investigation A quick search of the codebase seems to show the culprit of this error here.
Perhaps the following line can simply be changed from:
- } else if (typeof v !== jsType && v !== null) {
+ } else if (typeof v !== jsType && v != null) {
(e.g. it avoid strict equality on the null
check to also include undefined
and avoid erroring in that case?)
Earlier up in validateModelFields()
it is already checking if the field is required:
if (isRequired && (v === null || v === undefined)) {
throw new Error(`Field ${name} is required`);
}
So my suggested change should be sufficient? I don’t know if there are other side-effects of this change that are undesired, or if the original exclusion of undefined
was intentional, but hopefully not?
Amplify Version 2.2.8
Issue Analytics
- State:
- Created 3 years ago
- Reactions:1
- Comments:8 (3 by maintainers)
Top GitHub Comments
Brilliant, thanks @wei I look forward to checking it out once it’s released on a stable version. Thanks for fixing this!
For the record, I believe #7044 fixes this issue which has been merged and accessible in
aws-amplify@unstable
for now.