Skip to content
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

Serializing an object that inherits from OneOfBase throws error #169

Open
Scryper opened this issue Jan 30, 2024 · 0 comments
Open

Serializing an object that inherits from OneOfBase throws error #169

Scryper opened this issue Jan 30, 2024 · 0 comments

Comments

@Scryper
Copy link

Scryper commented Jan 30, 2024

Hi, I recently used OneOf to make some code quality improvements and encoutered an issue when serializing data.

I have an endpoint (.NET 6 API) in which I can return multiple types for the same response code. I know it is not a good thing, but it can't be changed due to business reasons. My goal here was to send this type of response to the front :

[GenerateOneOf]
public partial class MyClass : OneOfBase<T0, T1, T2> {}

// Sent like this : 
public IActionResult MyMethod() {
    var myClassInstance = this.MyOtherMethod();
    return this.Ok(myClassInstance)
}

// The goal was to be able to get the right type in my front : 
new MyService().MyMethod().then(result => this.data = result.isT0 ? result.asT0 : null)

The thing is, it can't be serialized as-is because of the exception thrown if the index does not correspond with the type currently used (cf. OneOfBase.AsT0).
As a workaround, I had to create a record in which I could copy the structure of MyClass :

public record OneOfResponseContainer<T0, T1, T2>(
    bool isT0,
    bool isT1,
    bool isT2,
    T0 valueT0,
    T1 valueT1,
    T2 valueT2);

new OneOfResponseContainer<T0, T1, T2>(
    response.IsT0,
    response.IsT1,
    response.IsT2,
    response.IsT0 ? (T0)response.Value : null,
    response.IsT1 ? (T1)response.Value : null,
    response.IsT2 ? (T2)response.Value : null);

I tried multiple solutions using other libraries to serialize MyClass but then it would not be the same structure, which is problematic as I generate my TS client using NSwag, so I would get undefined value for the object properties when handling the promise response. Also, custom converters would not be triggered so I wasn't able to handling the serializing as I want.
Was I missing something for serializing as I wanted, or is this something not supported at the moment ?

I think it would be useful if the objects inheriting from OneOfBase could be serialized with AsTx as null if x does not correspond to the index of the type used.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant