-
Notifications
You must be signed in to change notification settings - Fork 0
/
bgd.go
72 lines (64 loc) · 1.78 KB
/
bgd.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
package decoder
import (
"encoding/json"
"fmt"
"github.com/lapis2411/card-generator/adapter"
"github.com/lapis2411/card-generator/domain"
"strconv"
)
// Converter is an interface for converting csv file
type (
// csvConverter is a struct for converting csv file
bgdDecoder struct {
csvDecoder
}
cardData []struct {
ID int `json:"id"`
Name string `json:"name"`
TextData []textData `json:"data"`
}
textData struct {
StyleID string `json:"styleID"`
Text string `json:"text"`
}
)
func NewBGDDecoder() adapter.Decoder {
return &bgdDecoder{}
}
// DecodeStyle は既存のものを使う (fileから読み込むことを想定)
//func (c *jsonDecoder) DecodeStyles(data []byte) (map[string]*domain.Style, error) {
//}
// DecodeCard returns information for generating cards by csv format byte array
func (c *bgdDecoder) DecodeCards(data []byte, styles map[string]*domain.Style) (map[string][]domain.FormattedText, error) {
var jc cardData
cds := make(map[string][]domain.FormattedText, 0)
err := json.Unmarshal(data, &jc)
if err != nil {
return nil, err
}
duplicate := map[string]struct{}{}
for _, v := range jc {
ids := strconv.Itoa(v.ID)
if _, exist := duplicate[ids]; exist {
return nil, fmt.Errorf("%s is duplicated", ids)
}
duplicate[ids] = struct{}{}
cds[ids], err = toFormattedText(v.TextData, styles)
if err != nil {
return nil, err
}
}
return cds, nil
}
func toFormattedText(td []textData, st map[string]*domain.Style) ([]domain.FormattedText, error) {
ft := make([]domain.FormattedText, 0, len(td))
for _, v := range td {
st, ok := st[v.StyleID]
if !ok {
fmt.Printf("%s", v.StyleID)
return nil, fmt.Errorf("style '%s' is undefined", v.StyleID)
}
ft = append(ft, domain.NewFormattedText(v.Text, st))
}
return ft, nil
}