Format Fabcar Chaincode in Idiomatic Go

Signed-off-by: Brett Logan <brett.t.logan@ibm.com>
This commit is contained in:
Brett Logan 2020-07-06 12:51:51 -04:00
parent df727853c8
commit 683ee8b347

View file

@ -7,7 +7,7 @@ package main
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"strconv" "log"
"github.com/hyperledger/fabric-contract-api-go/contractapi" "github.com/hyperledger/fabric-contract-api-go/contractapi"
) )
@ -34,24 +34,24 @@ type QueryResult struct {
// InitLedger adds a base set of cars to the ledger // InitLedger adds a base set of cars to the ledger
func (s *SmartContract) InitLedger(ctx contractapi.TransactionContextInterface) error { func (s *SmartContract) InitLedger(ctx contractapi.TransactionContextInterface) error {
cars := []Car{ cars := []Car{
Car{Make: "Toyota", Model: "Prius", Colour: "blue", Owner: "Tomoko"}, {Make: "Toyota", Model: "Prius", Colour: "blue", Owner: "Tomoko"},
Car{Make: "Ford", Model: "Mustang", Colour: "red", Owner: "Brad"}, {Make: "Ford", Model: "Mustang", Colour: "red", Owner: "Brad"},
Car{Make: "Hyundai", Model: "Tucson", Colour: "green", Owner: "Jin Soo"}, {Make: "Hyundai", Model: "Tucson", Colour: "green", Owner: "Jin Soo"},
Car{Make: "Volkswagen", Model: "Passat", Colour: "yellow", Owner: "Max"}, {Make: "Volkswagen", Model: "Passat", Colour: "yellow", Owner: "Max"},
Car{Make: "Tesla", Model: "S", Colour: "black", Owner: "Adriana"}, {Make: "Tesla", Model: "S", Colour: "black", Owner: "Adriana"},
Car{Make: "Peugeot", Model: "205", Colour: "purple", Owner: "Michel"}, {Make: "Peugeot", Model: "205", Colour: "purple", Owner: "Michel"},
Car{Make: "Chery", Model: "S22L", Colour: "white", Owner: "Aarav"}, {Make: "Chery", Model: "S22L", Colour: "white", Owner: "Aarav"},
Car{Make: "Fiat", Model: "Punto", Colour: "violet", Owner: "Pari"}, {Make: "Fiat", Model: "Punto", Colour: "violet", Owner: "Pari"},
Car{Make: "Tata", Model: "Nano", Colour: "indigo", Owner: "Valeria"}, {Make: "Tata", Model: "Nano", Colour: "indigo", Owner: "Valeria"},
Car{Make: "Holden", Model: "Barina", Colour: "brown", Owner: "Shotaro"}, {Make: "Holden", Model: "Barina", Colour: "brown", Owner: "Shotaro"},
} }
for i, car := range cars { for i, car := range cars {
carAsBytes, _ := json.Marshal(car) carAsBytes, _ := json.Marshal(car)
err := ctx.GetStub().PutState("CAR"+strconv.Itoa(i), carAsBytes) key := fmt.Sprintf("CAR%d", i)
err := ctx.GetStub().PutState(key, carAsBytes)
if err != nil { if err != nil {
return fmt.Errorf("Failed to put to world state. %s", err.Error()) return fmt.Errorf("failed to put to world state. %v", err)
} }
} }
@ -66,86 +66,79 @@ func (s *SmartContract) CreateCar(ctx contractapi.TransactionContextInterface, c
Colour: colour, Colour: colour,
Owner: owner, Owner: owner,
} }
carAsBytes, err := json.Marshal(car)
carAsBytes, _ := json.Marshal(car) if err != nil {
return fmt.Errorf("failed marshalling to json: %v", err)
}
return ctx.GetStub().PutState(carNumber, carAsBytes) return ctx.GetStub().PutState(carNumber, carAsBytes)
} }
// QueryCar returns the car stored in the world state with given id // QueryCar returns the car stored in the world state with given id
func (s *SmartContract) QueryCar(ctx contractapi.TransactionContextInterface, carNumber string) (*Car, error) { func (s *SmartContract) QueryCar(ctx contractapi.TransactionContextInterface, carNumber string) (*Car, error) {
carAsBytes, err := ctx.GetStub().GetState(carNumber) carAsBytes, err := ctx.GetStub().GetState(carNumber)
if err != nil { if err != nil {
return nil, fmt.Errorf("Failed to read from world state. %s", err.Error()) return nil, fmt.Errorf("failed to read from world state: %v", err)
} }
if carAsBytes == nil { if carAsBytes == nil {
return nil, fmt.Errorf("%s does not exist", carNumber) return nil, fmt.Errorf("%s does not exist", carNumber)
} }
var car *Car
car := new(Car) err = json.Unmarshal(carAsBytes, car)
_ = json.Unmarshal(carAsBytes, car) if err != nil {
return nil, err
}
return car, nil return car, nil
} }
// QueryAllCars returns all cars found in world state // QueryAllCars returns all cars found in world state
func (s *SmartContract) QueryAllCars(ctx contractapi.TransactionContextInterface) ([]QueryResult, error) { func (s *SmartContract) QueryAllCars(ctx contractapi.TransactionContextInterface) ([]QueryResult, error) {
startKey := "" // Return all cars by using empty startKey and endKey
endKey := "" resultsIterator, err := ctx.GetStub().GetStateByRange("", "")
resultsIterator, err := ctx.GetStub().GetStateByRange(startKey, endKey)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer resultsIterator.Close() defer resultsIterator.Close()
results := []QueryResult{} var results []QueryResult
for resultsIterator.HasNext() { for resultsIterator.HasNext() {
queryResponse, err := resultsIterator.Next() queryResponse, err := resultsIterator.Next()
if err != nil { if err != nil {
return nil, err return nil, err
} }
car := new(Car) var car *Car
_ = json.Unmarshal(queryResponse.Value, car) err = json.Unmarshal(queryResponse.Value, car)
if err != nil {
return nil, fmt.Errorf("failed marshalling to json: %v", err)
}
queryResult := QueryResult{Key: queryResponse.Key, Record: car} queryResult := QueryResult{Key: queryResponse.Key, Record: car}
results = append(results, queryResult) results = append(results, queryResult)
} }
return results, nil return results, nil
} }
// ChangeCarOwner updates the owner field of car with given id in world state // ChangeCarOwner updates the owner field of car with given id in world state
func (s *SmartContract) ChangeCarOwner(ctx contractapi.TransactionContextInterface, carNumber string, newOwner string) error { func (s *SmartContract) ChangeCarOwner(ctx contractapi.TransactionContextInterface, carNumber string, newOwner string) error {
car, err := s.QueryCar(ctx, carNumber) car, err := s.QueryCar(ctx, carNumber)
if err != nil { if err != nil {
return err return err
} }
car.Owner = newOwner car.Owner = newOwner
carAsBytes, err := json.Marshal(car)
carAsBytes, _ := json.Marshal(car) if err != nil {
return fmt.Errorf("failed marshalling to json: %v", err)
}
return ctx.GetStub().PutState(carNumber, carAsBytes) return ctx.GetStub().PutState(carNumber, carAsBytes)
} }
func main() { func main() {
chaincode, err := contractapi.NewChaincode(&SmartContract{})
chaincode, err := contractapi.NewChaincode(new(SmartContract))
if err != nil { if err != nil {
fmt.Printf("Error create fabcar chaincode: %s", err.Error()) log.Panicf("Error create fabcar chaincode: %v", err)
return
} }
if err := chaincode.Start(); err != nil { if err := chaincode.Start(); err != nil {
fmt.Printf("Error starting fabcar chaincode: %s", err.Error()) log.Panicf("Error starting fabcar chaincode: %v", err)
} }
} }