From e9f2ad42ee589bc89a62e86d240cc2933c589d8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Macedo?= Date: Fri, 7 Jul 2023 06:46:02 -0300 Subject: [PATCH] :sparkles: Implement History in the manner of Search --- assets/history.go | 63 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 assets/history.go diff --git a/assets/history.go b/assets/history.go new file mode 100644 index 0000000..e730d5a --- /dev/null +++ b/assets/history.go @@ -0,0 +1,63 @@ +package assets + +import ( + "encoding/json" + "net/http" + + "github.com/goledgerdev/cc-tools/errors" + sw "github.com/goledgerdev/cc-tools/stubwrapper" + "github.com/hyperledger/fabric-chaincode-go/shim" + pb "github.com/hyperledger/fabric-protos-go/peer" +) + +type HistoryResponse struct { + Result []map[string]interface{} `json:"result"` + Metadata *pb.QueryResponseMetadata `json:"metadata"` +} + +func History(stub *sw.StubWrapper, key string, resolve bool) (*HistoryResponse, errors.ICCError) { + var resultsIterator shim.HistoryQueryIteratorInterface + // var responseMetadata *pb.QueryResponseMetadata + + resultsIterator, err := stub.GetHistoryForKey(key) + if err != nil { + return nil, errors.WrapErrorWithStatus(err, "failed to get history for key", http.StatusInternalServerError) + } + defer resultsIterator.Close() + + historyResult := make([]map[string]interface{}, 0) + + for resultsIterator.HasNext() { + queryResponse, err := resultsIterator.Next() + if err != nil { + return nil, errors.WrapErrorWithStatus(err, "error iterating response", 500) + } + + var data map[string]interface{} + + err = json.Unmarshal(queryResponse.Value, &data) + if err != nil { + return nil, errors.WrapErrorWithStatus(err, "failed to unmarshal queryResponse values", 500) + } + + if resolve { + key, err := NewKey(data) + if err != nil { + return nil, errors.WrapError(err, "failed to create key object to resolve result") + } + asset, err := key.GetRecursive(stub) + if err != nil { + return nil, errors.WrapError(err, "failed to resolve result") + } + data = asset + } + + historyResult = append(historyResult, data) + } + + response := HistoryResponse{ + Result: historyResult, + } + + return &response, nil +}