forked from jschoedt/go-firestorm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrud.go
69 lines (58 loc) · 1.63 KB
/
crud.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
package firestorm
import (
"cloud.google.com/go/firestore"
"context"
)
type contextKey string
func (c contextKey) String() string {
return "context key " + string(c)
}
var (
transactionCtxKey = contextKey("transaction")
)
func getTransaction(ctx context.Context) (*firestore.Transaction, bool) {
t, ok := ctx.Value(transactionCtxKey).(*firestore.Transaction)
return t, ok
}
func get(ctx context.Context, ref *firestore.DocumentRef) (*firestore.DocumentSnapshot, error) {
if t, ok := getTransaction(ctx); ok {
return t.Get(ref)
}
return ref.Get(ctx)
}
func getAll(ctx context.Context, client *firestore.Client, refs []*firestore.DocumentRef) ([]*firestore.DocumentSnapshot, error) {
if len(refs) == 0 {
return []*firestore.DocumentSnapshot{}, nil
}
if t, ok := getTransaction(ctx); ok {
return t.GetAll(refs)
}
return client.GetAll(ctx, refs)
}
func query(ctx context.Context, query firestore.Query) ([]*firestore.DocumentSnapshot, error) {
if t, ok := getTransaction(ctx); ok {
return t.Documents(query).GetAll()
}
return query.Documents(ctx).GetAll()
}
func create(ctx context.Context, ref *firestore.DocumentRef, m map[string]interface{}) error {
if t, ok := getTransaction(ctx); ok {
return t.Create(ref, m)
}
_, err := ref.Create(ctx, m)
return err
}
func set(ctx context.Context, ref *firestore.DocumentRef, m map[string]interface{}) error {
if t, ok := getTransaction(ctx); ok {
return t.Set(ref, m)
}
_, err := ref.Set(ctx, m)
return err
}
func del(ctx context.Context, ref *firestore.DocumentRef) error {
if t, ok := getTransaction(ctx); ok {
return t.Delete(ref)
}
_, err := ref.Delete(ctx)
return err
}