-
Notifications
You must be signed in to change notification settings - Fork 0
/
export.go
139 lines (119 loc) · 2.42 KB
/
export.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package main
import (
"bytes"
"context"
"encoding/csv"
"fmt"
"log"
"github.com/graphql-services/go-saga/graphqlorm"
)
const (
QUERY_SURVEY_EXPORT = `
query ($answerIDs: [ID!]) {
result: surveyExport(
filter: { answerIDs: $answerIDs }
) {
fields {
key
title
}
rows{
answer{
id
surveyId
}
values {
key
value
text
}
}
}
}
`
)
type SurveyExportField struct {
Key string
Title string
}
type SurveyExportRowValue struct {
Key string
Value string
Text string
}
type SurveyExportRowAnswer struct {
ID string
SurveyID string
}
type SurveyExportRow struct {
Values []SurveyExportRowValue
}
type SurveyExport struct {
Fields []SurveyExportField
Rows []SurveyExportRow
}
type SurveyExportQuery struct {
Result SurveyExport
}
func handleExport(ctx context.Context, client *graphqlorm.ORMClient, meta ExportMeta) (fileID string, err error) {
var query SurveyExportQuery
err = client.SendQuery(ctx, QUERY_SURVEY_EXPORT, map[string]interface{}{
"answerIDs": meta.AnswerIDs,
}, &query)
if err != nil {
return
}
csv, err := buildCSV(ctx, query.Result, meta)
if err != nil {
return
}
fmt.Println("final csv", string(csv))
fileID, err = uploadCSVFile(ctx, csv, "survey-export.csv")
return
}
func buildCSV(ctx context.Context, se SurveyExport, meta ExportMeta) (csvContent []byte, err error) {
for _, field := range se.Fields {
fmt.Println("field: ", field.Key, "=>", field.Title)
}
header := []string{}
hasRowNames := meta.RowNames != nil
if hasRowNames {
header = append(header, "")
}
for _, field := range se.Fields {
header = append(header, field.Key)
}
records := [][]string{
header,
}
for i, row := range se.Rows {
values := map[string]string{}
for _, val := range row.Values {
if val.Text != "" {
values[val.Key] = val.Text
} else {
values[val.Key] = val.Value
}
}
rowValues := []string{}
if hasRowNames {
if len(meta.RowNames) > i {
rowValues = append(rowValues, meta.RowNames[i])
} else {
rowValues = append(rowValues, "–")
}
}
for _, field := range se.Fields {
rowValues = append(rowValues, values[field.Key])
}
records = append(records, rowValues)
}
buf := bytes.NewBufferString("")
w := csv.NewWriter(buf)
w.WriteAll(records) // calls Flush internally
if err := w.Error(); err != nil {
log.Fatalln("error writing csv:", err)
}
csvContent = buf.Bytes()
return
}