Created
November 10, 2019 14:25
-
-
Save chhaileng/7c2ed881b8c2bd8f0527aa9e048ae7cb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"strconv" | |
"github.com/hyperledger/fabric/core/chaincode/shim" | |
"github.com/hyperledger/fabric/protos/peer" | |
) | |
// GetStudents : Get student by page | |
func (cc *SmartContract) GetStudents(stub shim.ChaincodeStubInterface, args []string) peer.Response { | |
if len(args) < 1 { | |
return shim.Error("{\"status\":false,\"error\":\"Invalid number of arguments. Expecting 1 argument\"}") | |
} | |
page, err := strconv.Atoi(args[0]) | |
if err != nil { | |
return shim.Error("{\"status\":false,\"error\":\"" + err.Error() + "\"}") | |
} | |
if page < 1 { | |
return shim.Error("{\"status\":false,\"error\":\"Page number must be > 0\"}") | |
} | |
queryString := "{\"selector\":{\"doc_type\":\"student\"},\"sort\":[\"student_id\"]}" | |
var pageSize int32 = 15 | |
bookmark := "" | |
pageCount := 0 | |
recordCount := 0 | |
var resultsIterator shim.StateQueryIteratorInterface | |
var responseMetadata *peer.QueryResponseMetadata | |
responseJSON := "{\"status\":true,\"message\":\"Success get students\",\"data\":[" | |
for true { | |
resultsIterator, responseMetadata, err = stub.GetQueryResultWithPagination(queryString, pageSize, bookmark) | |
if err != nil { | |
return shim.Error(err.Error()) | |
} | |
if bookmark == responseMetadata.Bookmark { | |
break | |
} | |
pageCount++ | |
if page == pageCount { | |
for resultsIterator.HasNext() { | |
resultKV, err := resultsIterator.Next() | |
if err != nil { | |
return shim.Error(err.Error()) | |
} | |
bytes := resultKV.GetValue() | |
var student Student | |
err = json.Unmarshal(bytes, &student) | |
if err != nil { | |
return shim.Error(err.Error()) | |
} | |
if recordCount != 0 { | |
responseJSON += "," | |
} | |
responseJSON += GetStudentJSON(student) | |
recordCount++ | |
} | |
responseJSON += "],\"paging\":{\"page\":" + strconv.Itoa(page) + ",\"count\":" + strconv.Itoa(recordCount) | |
} | |
// responseMetadata will be "nil" if the record is 0 at first page | |
bookmark = responseMetadata.Bookmark | |
if responseMetadata.Bookmark == "nil" { | |
break | |
} | |
resultsIterator.Close() | |
} | |
responseJSON += ",\"total_page\":" + strconv.Itoa(pageCount) + "}}" | |
if page > pageCount { | |
return shim.Error("{\"status\":false,\"error\":\"Invalid page number, only " + strconv.Itoa(pageCount) + " page(s) available.\"}") | |
} | |
return shim.Success([]byte(responseJSON)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment