-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdna.go
67 lines (58 loc) · 1.35 KB
/
dna.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
package main
import (
"cloud.google.com/go/datastore"
"context"
mutant "github.com/jhonynet/dna"
)
// structure for dna record
type DnaRecord struct {
Id string `json:"id"`
Dna mutant.Dna `json:"name"`
IsMutant bool `json:"isMutant"`
}
func getDnaKey(id string) *datastore.Key {
return datastore.NameKey("Dna", id, nil)
}
// get dna by uid
func getDnaById(id string) (*DnaRecord, error) {
var dna DnaRecord
ctx := context.Background()
k := getDnaKey(id)
if err := dsClient.Get(ctx, k, &dna); err != nil {
return nil, err
}
return &dna, nil
}
// create dna if not exists
func createDna(dna mutant.Dna, isMutant bool) (*DnaRecord, error) {
ctx := context.Background()
uid := mutant.BuildUniqueId(dna)
record, err := getDnaById(uid)
if err != nil && err.Error() != "datastore: no such entity" {
return record, err
}
// if record exists avoid creation
if record != nil && record.Id != "" {
return record, nil
}
// create new record and save
var newRecord = DnaRecord{
Id: uid,
Dna: dna,
IsMutant: isMutant,
}
// save
if _, err := dsClient.Put(ctx, getDnaKey(uid), &newRecord); err != nil {
return &newRecord, err
}
// if save is ok increase stats
if isMutant {
err = IncreaseStat("mutant")
} else {
err = IncreaseStat("human")
}
if err != nil {
return &newRecord, err
}
return &newRecord, nil
}