-
Notifications
You must be signed in to change notification settings - Fork 0
/
writer.go
51 lines (47 loc) · 1.21 KB
/
writer.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
package writer
import (
"cloud.google.com/go/firestore"
"context"
"fmt"
"reflect"
)
type Writer[T any] struct {
collection *firestore.CollectionRef
idx int
Map func(T)
isPointer bool
}
func NewWriter[T any](client *firestore.Client, collectionName string, opts ...func(T)) *Writer[T] {
var t T
modelType := reflect.TypeOf(t)
isPointer := false
if modelType.Kind() == reflect.Ptr {
modelType = modelType.Elem()
isPointer = true
}
idx := FindIdField(modelType)
if idx < 0 {
panic("Require Id field of " + modelType.Name() + " struct define _id bson tag.")
}
idField := modelType.Field(idx)
if idField.Type.String() != "string" {
panic(fmt.Sprintf("%s type of %s struct must be string", modelType.Field(idx).Name, modelType.Name()))
}
var mp func(T)
if len(opts) >= 1 {
mp = opts[0]
}
collection := client.Collection(collectionName)
return &Writer[T]{collection: collection, idx: idx, Map: mp, isPointer: isPointer}
}
func (w *Writer[T]) Write(ctx context.Context, model T) error {
if w.Map != nil {
w.Map(model)
}
vo := reflect.ValueOf(model)
if w.isPointer {
vo = reflect.Indirect(vo)
}
id := vo.Field(w.idx).Interface().(string)
return Save(ctx, w.collection, id, model)
}