-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdoc.go
86 lines (65 loc) · 1.45 KB
/
doc.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package surrealhigh
import (
"encoding/json"
"fmt"
"github.com/google/uuid"
"github.com/surrealdb/surrealdb.go"
)
type Doc interface {
Table() Table
}
type doc struct {
from Table
}
func (doc doc) Table() Table {
return doc.from
}
// DBDoc is a low level document as it has a reference to the database driver
type DBDoc interface {
Doc
json.Marshaler
Create() (Id, error)
db() SurrealDB
}
func NewDefaultDoc(doc Doc, db SurrealDriver) DefaultDoc {
return DefaultDoc{
doc: doc,
driver: db.Driver(),
}
}
type DefaultDoc struct {
doc Doc
driver SurrealDB
}
var _ DBDoc = DefaultDoc{}
func (doc DefaultDoc) Table() Table {
return doc.doc.Table()
}
func (doc DefaultDoc) MarshalJSON() ([]byte, error) {
return json.Marshal(doc.doc)
}
func (doc DefaultDoc) db() SurrealDB {
return doc.driver
}
var nilID = Id(uuid.Nil)
func (doc DefaultDoc) Create() (Id, error) {
// TODO(malikbenkirane) rm
errWrapf := func(f string, a ...interface{}) (Id, error) {
return nilID, fmt.Errorf(f, a...)
}
data, err := doc.db().Create(string(NewID().Thing(doc.Table())), doc.doc)
if err != nil {
return errWrapf("sdb: create: %w", err)
}
var docId struct {
RawId string `json:"id"`
}
if err := surrealdb.Unmarshal(data, &docId); err != nil {
return errWrapf("unmarshal docId: %w", err)
}
recId, err := NewIDFromThing(Thing(docId.RawId), doc.Table())
if err != nil {
return errWrapf("new id from thing: %w", err)
}
return recId, nil
}