@@ -23,6 +23,7 @@ type Inserter struct {
23
23
func NewInserter (client * firestore.Client ) * Inserter {
24
24
return & Inserter {
25
25
client : client ,
26
+ refIDs : map [string ]string {},
26
27
}
27
28
}
28
29
@@ -83,13 +84,13 @@ func (i *Inserter) executeJSON(ctx context.Context, cn, path string) error {
83
84
if ! ok {
84
85
continue
85
86
}
86
- err := i .createItem (ctx , cn , mp )
87
+ err := i .createItem (ctx , cn , jm . Ref , mp )
87
88
if err != nil {
88
89
return xerrors .Errorf ("failed to create item in array (index=%d): %w" , idx , err )
89
90
}
90
91
}
91
92
} 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 )
93
94
if err != nil {
94
95
return xerrors .Errorf ("failed to create item: %w" , err )
95
96
}
@@ -100,14 +101,23 @@ func (i *Inserter) executeJSON(ctx context.Context, cn, path string) error {
100
101
return nil
101
102
}
102
103
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 {
104
105
item = i .tryParseDate (item )
106
+ item = i .setRefs (item )
105
107
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 )
108
110
if err != nil {
109
111
return xerrors .Errorf ("failed to create item: %w" , err )
110
112
}
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
+
111
121
return nil
112
122
}
113
123
@@ -129,3 +139,23 @@ func (i *Inserter) tryParseDate(item map[string]interface{}) map[string]interfac
129
139
130
140
return item
131
141
}
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