github.com/s7techlab/cckit@v0.10.5/examples/cars/cars.go (about) 1 // Simple CRUD chaincode for store information about cars 2 package cars 3 4 import ( 5 "time" 6 7 "github.com/s7techlab/cckit/extensions/owner" 8 "github.com/s7techlab/cckit/router" 9 p "github.com/s7techlab/cckit/router/param" 10 ) 11 12 const CarEntity = `CAR` 13 const CarRegisteredEvent = `CAR_REGISTERED` 14 15 // CarPayload chaincode method argument 16 type CarPayload struct { 17 Id string 18 Title string 19 Owner string 20 } 21 22 // Car struct for chaincode state 23 type Car struct { 24 Id string 25 Title string 26 Owner string 27 28 UpdatedAt time.Time // set by chaincode method 29 } 30 31 // Key for car entry in chaincode state 32 func (c Car) Key() ([]string, error) { 33 return []string{CarEntity, c.Id}, nil 34 } 35 36 func New() *router.Chaincode { 37 r := router.New(`cars`) // also initialized logger with "cars" prefix 38 39 r.Init(invokeInit) 40 41 r.Group(`car`). 42 Query(`List`, queryCars). // chain code method name is carList 43 Query(`Get`, queryCar, p.String(`id`)). // chain code method name is carGet, method has 1 string argument "id" 44 Invoke(`Register`, invokeCarRegister, p.Struct(`car`, &CarPayload{}), // 1 struct argument 45 owner.Only) // allow access to method only for chaincode owner (authority) 46 47 return router.NewChaincode(r) 48 } 49 50 // ======= Init ================== 51 func invokeInit(c router.Context) (interface{}, error) { 52 return owner.SetFromCreator(c) 53 } 54 55 // ======= Chaincode methods ===== 56 57 // car get info chaincode method handler 58 func queryCar(c router.Context) (interface{}, error) { 59 // get state entry by composite key using CarKeyPrefix and car.Id 60 // and unmarshal from []byte to Car struct 61 return c.State().Get(&Car{Id: c.ParamString(`id`)}) 62 } 63 64 // cars car list chaincode method handler 65 func queryCars(c router.Context) (interface{}, error) { 66 return c.State().List( 67 CarEntity, // get list of state entries of type CarKeyPrefix 68 &Car{}) // unmarshal from []byte and append to []Car slice 69 } 70 71 // carRegister car register chaincode method handler 72 func invokeCarRegister(c router.Context) (interface{}, error) { 73 // arg name defined in router method definition 74 p := c.Param(`car`).(CarPayload) 75 76 t, _ := c.Time() // tx time 77 car := &Car{ // data for chaincode state 78 Id: p.Id, 79 Title: p.Title, 80 Owner: p.Owner, 81 UpdatedAt: t, 82 } 83 84 // trigger multiple event 85 if err := c.Event().Set(CarRegisteredEvent+`First`, car); err != nil { 86 return nil, err 87 } 88 89 if err := c.Event().Set(CarRegisteredEvent, car); err != nil { 90 return nil, err 91 } 92 93 return car, // peer.Response payload will be json serialized car data 94 //put json serialized data to state 95 // create composite key using CarKeyPrefix and car.Id 96 c.State().Insert(car) 97 }