Skip to content

Commit 3f74b32

Browse files
committed
feat ref id
1 parent b435895 commit 3f74b32

File tree

1 file changed

+35
-5
lines changed

1 file changed

+35
-5
lines changed

pkg/inserter/inserter.go

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ type Inserter struct {
2323
func NewInserter(client *firestore.Client) *Inserter {
2424
return &Inserter{
2525
client: client,
26+
refIDs: map[string]string{},
2627
}
2728
}
2829

@@ -83,13 +84,13 @@ func (i *Inserter) executeJSON(ctx context.Context, cn, path string) error {
8384
if !ok {
8485
continue
8586
}
86-
err := i.createItem(ctx, cn, mp)
87+
err := i.createItem(ctx, cn, jm.Ref, mp)
8788
if err != nil {
8889
return xerrors.Errorf("failed to create item in array (index=%d): %w", idx, err)
8990
}
9091
}
9192
} else if payload, ok := jm.Payload.(map[string]interface{}); ok {
92-
err := i.createItem(ctx, cn, payload)
93+
err := i.createItem(ctx, cn, jm.Ref, payload)
9394
if err != nil {
9495
return xerrors.Errorf("failed to create item: %w", err)
9596
}
@@ -100,14 +101,23 @@ func (i *Inserter) executeJSON(ctx context.Context, cn, path string) error {
100101
return nil
101102
}
102103

103-
func (i *Inserter) createItem(ctx context.Context, cn string, item map[string]interface{}) error {
104+
func (i *Inserter) createItem(ctx context.Context, cn, refID string, item map[string]interface{}) error {
104105
item = i.tryParseDate(item)
106+
item = i.setRefs(item)
105107

106-
log.Printf("collection: %s, item: %+v", cn, item)
107-
_, err := i.client.Collection(cn).NewDoc().Create(ctx, item)
108+
d := i.client.Collection(cn).NewDoc()
109+
_, err := d.Create(ctx, item)
108110
if err != nil {
109111
return xerrors.Errorf("failed to create item: %w", err)
110112
}
113+
114+
if refID != "" {
115+
if _, ok := i.refIDs[refID]; ok {
116+
return xerrors.Errorf("already ref id: %s", refID)
117+
}
118+
i.refIDs[refID] = d.ID
119+
}
120+
111121
return nil
112122
}
113123

@@ -129,3 +139,23 @@ func (i *Inserter) tryParseDate(item map[string]interface{}) map[string]interfac
129139

130140
return item
131141
}
142+
143+
func (i *Inserter) setRefs(item map[string]interface{}) map[string]interface{} {
144+
for k, v := range item {
145+
switch vt := v.(type) {
146+
case string:
147+
if strings.HasPrefix(vt, "$") {
148+
refID := strings.TrimPrefix(vt, "$")
149+
rv, ok := i.refIDs[refID]
150+
if !ok {
151+
log.Printf("%s was not found", refID)
152+
continue
153+
}
154+
item[k] = rv
155+
}
156+
}
157+
}
158+
159+
return item
160+
161+
}

0 commit comments

Comments
 (0)