-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
69 lines (59 loc) · 1.75 KB
/
Copy pathexample_test.go
File metadata and controls
69 lines (59 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package codemode_test
import (
"context"
"encoding/json"
"fmt"
"github.com/meigma/codemode"
"github.com/meigma/codemode/authz"
)
// Example_registerAndExecute registers one typed capability and prints main's final value.
//
// authz.AllowAll is deliberate in this sample. Production hosts normally supply
// an Authorizer that inspects the trusted subject and canonical arguments.
func Example_registerAndExecute() {
// lookupInput is the records.lookup argument contract.
type lookupInput struct {
// Key is the required record identifier.
Key string `json:"key"`
// Limit is the optional result bound.
Limit *int64 `json:"limit,omitempty"`
}
// lookupOutput is the records.lookup handler result.
type lookupOutput struct {
// Key is the looked-up record identifier.
Key string `json:"key"`
// Count is the resolved optional limit, or zero when omitted.
Count int64 `json:"count"`
}
builder := codemode.New(codemode.Options{Authorizer: authz.AllowAll()})
codemode.Register(builder, codemode.Capability[lookupInput, lookupOutput]{
Name: "records.lookup",
Summary: "Look up one record by key.",
Handler: func(_ context.Context, _ authz.Subject, input lookupInput) (lookupOutput, error) {
count := int64(0)
if input.Limit != nil {
count = *input.Limit
}
return lookupOutput{Key: input.Key, Count: count}, nil
},
})
server, err := builder.Build()
if err != nil {
panic(err)
}
result, err := server.Execute(context.Background(), authz.Subject{ID: "example-user"}, `
print("discarded")
def main():
return records.lookup(key="alpha", limit=2)
`)
if err != nil {
panic(err)
}
encoded, err := json.Marshal(result)
if err != nil {
panic(err)
}
fmt.Println(string(encoded))
// Output:
// {"count":2,"key":"alpha"}
}