New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Polymorphic JSON field #2491
Comments
Hey @kpeu3i and thanks for opening this issue 👋 You can use a custom type that implements the json.Marshaler/json.Unmarshaler interfaces, store a field named For example, for a field type Addr struct{ net.Addr }
func (a *Addr) UnmarshalJSON(data []byte) error {
var types struct {
TCP *net.TCPAddr `json:"tcp,omitempty"`
UDP *net.UDPAddr `json:"udp,omitempty"`
}
if err := json.Unmarshal(data, &types); err != nil {
return err
}
switch {
case types.TCP != nil && types.UDP != nil:
return errors.New("TCP and UDP addresses are mutually exclusive")
case types.TCP != nil:
a.Addr = types.TCP
case types.UDP != nil:
a.Addr = types.UDP
}
return nil
}
func (a Addr) MarshalJSON() ([]byte, error) {
var types struct {
TCP *net.TCPAddr `json:"tcp,omitempty"`
UDP *net.UDPAddr `json:"udp,omitempty"`
}
switch a := a.Addr.(type) {
case *net.TCPAddr:
types.TCP = a
case *net.UDPAddr:
types.UDP = a
default:
return nil, fmt.Errorf("unsupported address type: %T", a)
}
return json.Marshal(types)
} I also added an example PR for your use-case in this repository, please give it a look #2497 Closing, but please feel free to reopen or join our Discord server if you still need help with this. |
@a8m thanks for your response. I got your idea. But I'm trying to switch to Ent from an existing database and I cannot modify the data structure that is stored inside the In terms of your example, The only way to detect which struct should be used is the value of |
To add my idea to this: You can use // in schema
field.Json("data", json.RawMessage{})
// With 1.18 you can use generics to return a union type
func (s MySchema) Data() Data1 | Data2 | Data3 {
switch s.Type {
case: ....
}
} Once read hooks/interceptors are present in Ent, this can be done similar to the mutation hooks. |
I think another nice solution for this is to use These fields can be added using custom templates or manually in an We can expose an API for calling custom functions in |
hehe, @masseelch 😆 @hedwigz and I just discussed this and we both commented this at the same time :) |
Guys, thanks for the help I will follow your suggestion about |
Hi, guys! I have a question about defining the JSON field which stores different structures depending on the entity type.
I know that I can define JSON like this:
But in my case, I need to have something like that:
because different structs are stored inside the data field.
So, is it possible somehow to choose the correct data structure when scanning the JSON field based on another field value from the entity (e.g type)?
The text was updated successfully, but these errors were encountered: