#php editor Apple will share with you today a problem about the key not existing when processing some updates. When making a PATCH request, sometimes you encounter a situation where the key does not exist. So how should we deal with it? In this article, we will introduce the methods and steps to solve this problem in detail to help you better deal with this situation and ensure the normal operation of the system. Let’s take a look!
I am trying to figure out how to solve this problem.
I have a user
structure with some fields on it. However, when decoding the json object for the patch user call, the missing key causes the value to be set to *nil. The corresponding database property is of type text null
, so when key is missing, the result will always be stored as null.
type updateuserdto struct { id uuid.uuid firstname string lastname string imageurl *string }
imageurl
Can be nil, but when the object is sent from the client:
{ firstName: "Jimmy" }
This will decode to imageurl
= nil because imageurl
does not exist in the json.
How do I handle partial updates without using map[string]struct{}
instead of my dto checking if each field exists?
You can implement a custom json.unmarshaler
to determine if the field is completely omitted, provided but its value is null
, or a non-null value is provided.
type optstring struct { isvalid bool string *string } // if a field with this type has no corresponding field in the // incoming json then this method will not be invoked and the // isvalid flag's value will remain `false`. func (s *optstring) unmarshaljson(data []byte) error { if err := json.unmarshal(data, &s.string); err != nil { return err } s.isvalid = true return nil }
type updateuserdto struct { id uuid.uuid firstname string lastname string imageurl optstring }
//m.sbmmt.com/link/22f791da07b0d8a2504c2537c560001c
Another way that doesn't require a custom type is to set the value of the go field to the value of the current database column before unmarshaling the json. If the incoming json does not contain matching fields, json.decoder
(used by json.unmarshal
) will not "touch" the target's fields.
dto := loadUpdateUserDTOFromDB(conn) if err := json.Unmarshal(data, dto); err != nil { return err }
//m.sbmmt.com/link/cdf49f5251e7b3eb4f009483121e9b64
The above is the detailed content of Handling PATCH partial updates when key does not exist. For more information, please follow other related articles on the PHP Chinese website!