-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathexample_test.go
71 lines (56 loc) · 1.83 KB
/
example_test.go
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
70
71
package usecase_test
import (
"context"
"fmt"
"log"
"github.com/swaggest/usecase"
"github.com/swaggest/usecase/status"
)
func ExampleNewIOI() {
// Configure use case interactor in application layer.
type myInput struct {
Param1 int `path:"param1" description:"Parameter in resource path." multipleOf:"2"`
Param2 string `json:"param2" description:"Parameter in resource body."`
}
type myOutput struct {
Value1 int `json:"value1"`
Value2 string `json:"value2"`
}
u := usecase.NewIOI(new(myInput), new(myOutput), func(ctx context.Context, input, output interface{}) error {
var (
in = input.(*myInput)
out = output.(*myOutput)
)
if in.Param1%2 != 0 {
return status.InvalidArgument
}
// Do something to set output based on input.
out.Value1 = in.Param1 + in.Param1
out.Value2 = in.Param2 + in.Param2
return nil
})
// Additional properties can be configured for purposes of automated documentation.
u.SetTitle("Doubler")
u.SetDescription("Doubler doubles parameter values.")
u.SetTags("transformation")
u.SetExpectedErrors(status.InvalidArgument)
u.SetIsDeprecated(true)
// The code below illustrates transport side.
// At transport layer, input and out ports are to be examined and populated using reflection.
// For example request body could be json unmarshaled, or request parameters can be mapped.
input := new(myInput)
// input := reflect.New(reflect.TypeOf(u.InputPort()))
input.Param1 = 1234
input.Param2 = "abc"
output := new(myOutput)
// output := reflect.New(reflect.TypeOf(u.OutputPort()))
// When input is prepared and output is initialized, transport should invoke interaction.
err := u.Interact(context.TODO(), input, output)
if err != nil {
log.Fatal(err)
}
// And make some use of prepared output.
fmt.Printf("%+v\n", output)
// Output:
// &{Value1:2468 Value2:abcabc}
}