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

Support getting underlying vale from oneOf type #1257

Open
abemedia opened this issue May 31, 2024 · 0 comments
Open

Support getting underlying vale from oneOf type #1257

abemedia opened this issue May 31, 2024 · 0 comments
Labels
enhancement New feature or request openapi-features OpenAPI features support issues

Comments

@abemedia
Copy link
Contributor

abemedia commented May 31, 2024

Description

When you define a oneOf type that has shared fields (e.g. ID) and you want to access this field, regardless of the underlying type, you need to perform a switch. If we had a method to return the underlying type as an interface it would make code less brittle as a new type being added to the spec would not need the switch to be updated in these circumstances.

See the example below:

description: Anything
oneOf:
  - $ref: ./Foo.yaml
  - $ref: ./Bar.yaml
  - $ref: ./Baz.yaml
  
discriminator:
  propertyName: type
  mapping:
    Foo: ./Foo.yaml
    Bar: ./Bar.yaml
    Baz: ./Baz.yaml
type Anything struct {
	Type  AnythingType // switch on this field
	Foo   Foo
	Bar   Bar
	Baz   Baz
}

// This is the method I'd like to see generated.
func (a Anything) GetValue() any {
	switch a.Type {
	case FooAnything:
		return a.Foo
	case BarAnything:
		return a.Bar
	case BazAnything:
		return a.Baz
	default:
		return nil
	}
}

This would allow code like this:

type GetIDer interface {
	GetID int64
}

func getID(a Anything) int64 {
	if v, ok := a.GetValue().(GetIDer); ok {
		return v.GetID()
	}
	return 0
}

Right now we cannot get around being very explicit such as the example below, with the added issue of it breaking if another type is added to the spec.

func getID(a Anything) int64 {
	switch a.Type {
	case FooAnything:
		return a.Foo.ID
	case BarAnything:
		return a.Bar.ID
	case BazAnything:
		return a.Baz.ID
	default:
		return 0
	}
}

References

@abemedia abemedia added enhancement New feature or request openapi-features OpenAPI features support issues labels May 31, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request openapi-features OpenAPI features support issues
Projects
None yet
Development

No branches or pull requests

1 participant