batchprofile.gno
1.54 Kb ยท 63 lines
1package batchprofile
2
3import (
4 "errors"
5
6 "gno.land/p/nt/ufmt"
7 "gno.land/p/onbloc/json"
8 zenaov1 "gno.land/p/zenao/zenao/v1"
9 "gno.land/r/demo/profile"
10)
11
12func Query(req *zenaov1.BatchProfileRequest) [][]interface{} {
13 res := make([][]interface{}, len(req.Addresses))
14 for i, addr := range req.Addresses {
15 res[i] = make([]interface{}, len(req.Fields))
16 for j, field := range req.Fields {
17 switch field.Type {
18 case "string":
19 res[i][j] = profile.GetStringField(address(addr), field.Key, "")
20 case "bool":
21 res[i][j] = profile.GetBoolField(address(addr), field.Key, false)
22 case "int":
23 res[i][j] = profile.GetIntField(address(addr), field.Key, 0)
24 default:
25 panic(ufmt.Errorf("invalid field type %q", field.Type))
26 }
27 }
28 }
29 return res
30}
31
32func queryJSON(reqJSON string) string {
33 j, err := json.UnmarshalSafe([]byte(reqJSON))
34 if err != nil {
35 panic(err)
36 }
37 req := &zenaov1.BatchProfileRequest{}
38 zenaov1.BatchProfileRequestFromJSON(req, j)
39
40 res := Query(req)
41 elems := make([]*json.Node, len(res))
42 for i, profile := range res {
43 row := make([]*json.Node, len(profile))
44 for j, field := range profile {
45 switch val := field.(type) {
46 case string:
47 row[j] = json.StringNode("", val)
48 case int:
49 row[j] = json.NumberNode("", float64(val))
50 case bool:
51 row[j] = json.BoolNode("", val)
52 default:
53 panic(errors.New("unexpected internal field type, should not happen"))
54 }
55 }
56 elems[i] = json.ArrayNode("", row)
57 }
58 bz, err := json.Marshal(json.ArrayNode("", elems))
59 if err != nil {
60 panic(err)
61 }
62 return string(bz)
63}