Skip to content

Commit

Permalink
rpc: make helpers handle empty-values for some types
Browse files Browse the repository at this point in the history
Turns out that protobuf does not send actual nils to handlers if the
request is empty, but always atleast allocates the zero value of said
type before the call. We check for some "required" fields now to determine
if we should return nil or not from the helper
  • Loading branch information
Wessie committed Jun 19, 2024
1 parent bdb19c7 commit d33a244
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
6 changes: 3 additions & 3 deletions rpc/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ func toProtoSongUpdate(s *radio.SongUpdate) *SongUpdate {
}

func fromProtoSongUpdate(s *SongUpdate) *radio.SongUpdate {
if s == nil {
if s == nil || (s.Song == nil && s.Info == nil) {
return nil
}
return &radio.SongUpdate{
Expand Down Expand Up @@ -214,7 +214,7 @@ func toProtoQueueID(rid radio.QueueID) *QueueID {
}

func fromProtoQueueID(id *QueueID) radio.QueueID {
if id == nil {
if id == nil || len(id.ID) == 0 {
return radio.QueueID{}
}

Expand Down Expand Up @@ -276,7 +276,7 @@ func toProtoUser(u *radio.User) *User {
}

func fromProtoUser(u *User) *radio.User {
if u == nil {
if u == nil || (u.Id == 0 && u.Username == "") {
return nil
}
return &radio.User{
Expand Down
8 changes: 6 additions & 2 deletions rpc/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func TestRoundtrip(tt *testing.T) {
// special generator for users since we don't actually pass all the fields
// over the wire for reasons
userGen := gen.Struct(reflect.TypeFor[radio.User](), map[string]gopter.Gen{
"ID": a.GenForType(reflect.TypeFor[radio.UserID]()),
"ID": a.GenForType(reflect.TypeFor[radio.UserID]()).SuchThat(func(v radio.UserID) bool { return v > 0 }),
"Username": gen.AnyString(),
"IP": gen.AnyString(),
"UpdatedAt": a.GenForType(reflect.TypeFor[*time.Time]()),
Expand Down Expand Up @@ -95,7 +95,11 @@ func TestRoundtrip(tt *testing.T) {
p.Property("user-permissions", a.ForAll(func(in radio.UserPermissions) bool {
out := fromProtoUserPermissions(toProtoUserPermissions(in))

return assert.Equal(tt, in, out)
if len(in) == 0 {
return assert.Len(tt, out, 0)
} else {
return assert.Equal(tt, in, out)
}
}))
p.Property("dj", a.ForAll(func(in radio.DJ) bool {
out := fromProtoDJ(toProtoDJ(in))
Expand Down

0 comments on commit d33a244

Please sign in to comment.