json encoding of result: [] instead of null if empty

This commit is contained in:
Wouter Groeneveld 2021-05-09 20:52:07 +02:00
parent b7a12b427f
commit 3b58d2031f
2 changed files with 53 additions and 3 deletions

View File

@ -50,17 +50,24 @@ type IndiewebDataResult struct {
} }
func ResultFailure(data []*IndiewebData) IndiewebDataResult { func ResultFailure(data []*IndiewebData) IndiewebDataResult {
return IndiewebDataResult{ return emptyNilData(IndiewebDataResult{
Status: "failure", Status: "failure",
Data: data, Data: data,
} })
} }
func ResultSuccess(data []*IndiewebData) IndiewebDataResult { func ResultSuccess(data []*IndiewebData) IndiewebDataResult {
return IndiewebDataResult{ return emptyNilData(IndiewebDataResult{
Status: "success", Status: "success",
Data: data, Data: data,
})
}
func emptyNilData(result IndiewebDataResult) IndiewebDataResult {
if result.Data == nil {
result.Data = make([]*IndiewebData, 0)
} }
return result
} }
type IndiewebData struct { type IndiewebData struct {

View File

@ -2,12 +2,55 @@ package mf
import ( import (
"brainbaking.com/go-jamming/common" "brainbaking.com/go-jamming/common"
"encoding/json"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"testing" "testing"
"time" "time"
"willnorris.com/go/microformats" "willnorris.com/go/microformats"
) )
func TestResultSuccessNonEmpty(t *testing.T) {
arr := make([]*IndiewebData, 1)
arr[0] = &IndiewebData{Author: IndiewebAuthor{Name: "Jaak"}}
data := ResultSuccess(arr)
jsonData, err := json.Marshal(data)
assert.NoError(t, err)
expected := `{"status":"success","json":[{"author":{"name":"Jaak","picture":""},"name":"","content":"","published":"","url":"","type":"","source":"","target":""}]}`
assert.Equal(t, expected, string(jsonData))
}
func TestResultSuccessEmptyEncodesAsEmptyJSONArray(t *testing.T) {
data := ResultSuccess(nil)
jsonData, err := json.Marshal(data)
assert.NoError(t, err)
expected := `{"status":"success","json":[]}`
assert.Equal(t, expected, string(jsonData))
}
func TestResultFailureNonEmpty(t *testing.T) {
arr := make([]*IndiewebData, 1)
arr[0] = &IndiewebData{Author: IndiewebAuthor{Name: "Jaak"}}
data := ResultFailure(arr)
jsonData, err := json.Marshal(data)
assert.NoError(t, err)
expected := `{"status":"failure","json":[{"author":{"name":"Jaak","picture":""},"name":"","content":"","published":"","url":"","type":"","source":"","target":""}]}`
assert.Equal(t, expected, string(jsonData))
}
func TestResultFailureEmptyEncodesAsEmptyJSONArray(t *testing.T) {
data := ResultFailure(nil)
jsonData, err := json.Marshal(data)
assert.NoError(t, err)
expected := `{"status":"failure","json":[]}`
assert.Equal(t, expected, string(jsonData))
}
func TestPublished(t *testing.T) { func TestPublished(t *testing.T) {
cases := []struct { cases := []struct {
label string label string