-
Notifications
You must be signed in to change notification settings - Fork 5
/
doc.go
103 lines (81 loc) · 1.8 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package core
import (
"encoding/json"
"errors"
"github.com/hyperledger/fabric-chaincode-go/shim"
)
// DocsKey is a key for documents
const DocsKey = "documents"
// Doc json struct
type Doc struct {
ID string `json:"id"`
Hash string `json:"hash"`
}
// DocumentsList returns list of documents
func DocumentsList(stub shim.ChaincodeStubInterface) ([]Doc, error) {
iter, err := stub.GetStateByPartialCompositeKey(DocsKey, []string{})
if err != nil {
return nil, err
}
defer func() {
_ = iter.Close()
}()
var result []Doc
for iter.HasNext() {
res, err := iter.Next()
if err != nil {
return nil, err
}
var doc Doc
err = json.Unmarshal(res.GetValue(), &doc)
if err != nil {
return nil, err
}
result = append(result, doc)
}
return result, nil
}
// AddDocs adds documents to the ledger
func AddDocs(stub shim.ChaincodeStubInterface, rawDocs string) error {
if rawDocs == "" {
return errors.New("wrong docs parameters")
}
var docs []*Doc
err := json.Unmarshal([]byte(rawDocs), &docs)
if err != nil {
return err
}
for _, doc := range docs {
if doc.ID == "" || doc.Hash == "" {
return errors.New("empty value of doc parameters")
}
key, err := stub.CreateCompositeKey(DocsKey, []string{doc.ID})
if err != nil {
return err
}
// check for the same docID
rawDoc, err := stub.GetState(key)
if err != nil {
return err
}
if len(rawDoc) > 0 {
continue
}
docJSON, err := json.Marshal(doc)
if err != nil {
return err
}
if err = stub.PutState(key, docJSON); err != nil {
return err
}
}
return nil
}
// DeleteDoc deletes document from the ledger
func DeleteDoc(stub shim.ChaincodeStubInterface, docID string) error {
key, err := stub.CreateCompositeKey(DocsKey, []string{docID})
if err != nil {
return err
}
return stub.DelState(key)
}