Have Exporter.Write automatically call ExportData on given data structure

This commit is contained in:
Mislav Marohnić 2021-05-11 18:25:20 +02:00
parent 026b07d1cf
commit 5f0301c990
10 changed files with 97 additions and 61 deletions

View file

@ -6,6 +6,7 @@ import (
)
func (issue *Issue) ExportData(fields []string) *map[string]interface{} {
v := reflect.ValueOf(issue).Elem()
data := map[string]interface{}{}
for _, f := range fields {
@ -25,7 +26,6 @@ func (issue *Issue) ExportData(fields []string) *map[string]interface{} {
case "projectCards":
data[f] = issue.ProjectCards.Nodes
default:
v := reflect.ValueOf(issue).Elem()
sf := fieldByName(v, f)
data[f] = sf.Interface()
}
@ -35,6 +35,7 @@ func (issue *Issue) ExportData(fields []string) *map[string]interface{} {
}
func (pr *PullRequest) ExportData(fields []string) *map[string]interface{} {
v := reflect.ValueOf(pr).Elem()
data := map[string]interface{}{}
for _, f := range fields {
@ -75,7 +76,6 @@ func (pr *PullRequest) ExportData(fields []string) *map[string]interface{} {
}
data[f] = &requests
default:
v := reflect.ValueOf(pr).Elem()
sf := fieldByName(v, f)
data[f] = sf.Interface()
}
@ -84,22 +84,6 @@ func (pr *PullRequest) ExportData(fields []string) *map[string]interface{} {
return &data
}
func ExportIssues(issues []Issue, fields []string) *[]interface{} {
data := make([]interface{}, len(issues))
for i := range issues {
data[i] = issues[i].ExportData(fields)
}
return &data
}
func ExportPRs(prs []PullRequest, fields []string) *[]interface{} {
data := make([]interface{}, len(prs))
for i := range prs {
data[i] = prs[i].ExportData(fields)
}
return &data
}
func fieldByName(v reflect.Value, field string) reflect.Value {
return v.FieldByNameFunc(func(s string) bool {
return strings.EqualFold(field, s)

View file

@ -90,31 +90,6 @@ func TestIssue_ExportData(t *testing.T) {
}
}
func TestExportIssues(t *testing.T) {
issues := []Issue{
{Milestone: Milestone{Title: "hi"}},
{},
}
exported := ExportIssues(issues, []string{"milestone"})
buf := bytes.Buffer{}
enc := json.NewEncoder(&buf)
enc.SetIndent("", "\t")
require.NoError(t, enc.Encode(exported))
assert.Equal(t, heredoc.Doc(`
[
{
"milestone": {
"title": "hi"
}
},
{
"milestone": null
}
]
`), buf.String())
}
func TestPullRequest_ExportData(t *testing.T) {
tests := []struct {
name string