-
I'm trying to figure out how to properly utilize oneOf. I'm able to get the properties in the schema itself, but how do I actually set values? Code may illustrate my issue: type OneOfViewData struct{}
type PossibleStruct1 struct {
Foo string
}
type PossibleStruct2 struct {
Bar string
}
var _ js.OneOfExposer = OneOfViewData{}
func (OneOfViewData) JSONSchemaOneOf() []interface{} {
return []interface{}{PossibleStruct1{}, PossibleStruct2{}}
}
type MyResponse struct {
Data OneOfViewData `json:"data"`
}
...
func (r *Routes) myHandler() *nethttp.Handler {
u := usecase.IOInteractor{}
u.Input = new(MyRequest)
u.Output = new(MyResponse)
u.Interactor = usecase.Interact(func(ctx context.Context, input, output interface{}) error {
var in = input.(*MyRequest)
var out = output.(*MyResponse)
//
out.Data <---- How do I set 'data' to PossibleStruct1 or 2?
return nil
})
return restspec.NewHandler(u)
} I can simply replace |
Beta Was this translation helpful? Give feedback.
Answered by
vearutop
Feb 11, 2023
Replies: 1 comment 1 reply
-
Hello, package usecase
import (
"context"
"encoding/json"
"github.com/swaggest/jsonschema-go"
"github.com/swaggest/usecase"
)
type OneOfViewData struct {
// Enumerate structures and disable default marshaling.
S1 *PossibleStruct1 `json:"-"`
S2 *PossibleStruct2 `json:"-"`
}
// MarshalJSON implements oneOf marshaling.
// UnmarshalJSON is skipped as this is only a response structure.
func (o OneOfViewData) MarshalJSON() ([]byte, error) {
if o.S1 != nil {
return json.Marshal(o.S1)
}
return json.Marshal(o.S2)
}
type PossibleStruct1 struct {
Foo string
}
type PossibleStruct2 struct {
Bar string
}
var _ jsonschema.OneOfExposer = OneOfViewData{}
func (OneOfViewData) JSONSchemaOneOf() []interface{} {
return []interface{}{PossibleStruct1{}, PossibleStruct2{}}
}
type MyResponse struct {
Data OneOfViewData `json:"data"`
}
type MyRequest struct {
Baz string `query:"baz"`
}
func OneOfUsecase() usecase.Interactor {
u := usecase.NewInteractor(func(ctx context.Context, in MyRequest, out *MyResponse) error {
if in.Baz == "s1" {
out.Data.S1 = &PossibleStruct1{Foo: "foo"}
} else {
out.Data.S2 = &PossibleStruct2{Bar: "bar"}
}
return nil
})
return u
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
NuSkooler
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello,
*Of
schema documentation is separated from actual parent structure, so you need to implement custom (un)marshaler too.Please check example (I also used generic API here, as it is now the recommended way to define an interactor).