deepcopier icon indicating copy to clipboard operation
deepcopier copied to clipboard

Optional Field Updates using `null.v4`

Open naftulikay opened this issue 3 years ago • 0 comments

So far, I'm benefiting a lot from this package, so thank you for the excellent work so far.

I mentioned this in #26 but this seems to merit its own issue.

In my REST API, I accept PATCH requests, which have all optional fields, so that you can update only what you'd like to:

type UpdateNewsRequest struct {
    Title null.String
    Description null.String
}

type News struct {
    ID uint
    Title string
    Description string
}

I'm converting it like so:

httpModel := UpdateNewsRequest {
    Title: null.StringFrom("new title")
}

dbModel := DatabaseModel {
    // fields...
   Title: "old title"
   Description: "leave me alone"
}

if err := deepcopier.Copy(&httpModel).To(&dbModel); err != nil {
    t.Fatalf("Could not deep copy: %s", err)
}

assert.Equal(t, httpModel.Title.ValueOrZero(), dbModel.Title)
assert.Equal(t, "leave me alone", dbModel.Description)

This currently fails at the first assertion, because deepcopier did not copy UpdateNewsRequest.Title, presumably because it is a null.String and deepcopier does not understand it.

I'm wondering how much work it would be to integrate this optional update feature, I'll have to look at the codebase and see if I can implement this. Alternatively, if there is a way using the context feature to accomplish this, that would be wonderful, but I don't exactly understand what the context feature does from trying it out.

naftulikay avatar Aug 28 '21 22:08 naftulikay