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

Use discriminator with several mappings for one schema #1530

Open
maks56893 opened this issue Apr 3, 2024 · 0 comments
Open

Use discriminator with several mappings for one schema #1530

maks56893 opened this issue Apr 3, 2024 · 0 comments

Comments

@maks56893
Copy link

maks56893 commented Apr 3, 2024

I would like to use two schemas in oneOf with discriminator. I have several enum values for each discriminator fields in schemas. So can I use discriminator like this?

ConfigSaveReq:
      oneOf:
      - $ref: "#/components/schemas/ConfigHttp"
      - $ref: "#/components/schemas/ConfigSsh"
      discriminator:
        propertyName: config_type
        mapping:
          ssh_server: "#/components/schemas/ConfigSsh"
          apache_server: "#/components/schemas/ConfigHttp"
          web_server: "#/components/schemas/ConfigHttp"
          another_server: "#/components/schemas/ConfigHttp"

Now after generating types I get switch with only two cases in ValueByDiscriminator(). Furthermore, for case with ConfigHttp variable value selecting randomly from ConfigHttp keys

	switch discriminator {
	case "ssh_server":
		return t.AsConfigSsh()
	case "web_server":
		return t.AsConfigHttp()
	default:
		return nil, errors.New("unknown discriminator value: " + discriminator)
	}

I found this break in generateUnion, if remove it and make len assertion by len(discriminator.Mapping) instead len(elements) my case will work. It is will fine?

		if discriminator != nil {
			if len(discriminator.Mapping) != 0 && element.Ref == "" {
				return errors.New("ambiguous discriminator.mapping: please replace inlined object with $ref")
			}

			// Explicit mapping.
			var mapped bool
			for k, v := range discriminator.Mapping {
				if v == element.Ref {
					outSchema.Discriminator.Mapping[k] = elementSchema.GoType
					mapped = true
					break <------
				}
			}
			// Implicit mapping.
			if !mapped {
				outSchema.Discriminator.Mapping[RefPathToObjName(element.Ref)] = elementSchema.GoType
			}
		}
jKiler added a commit to jKiler/oapi-codegen that referenced this issue Apr 8, 2024
jKiler added a commit to jKiler/oapi-codegen that referenced this issue Apr 8, 2024
jKiler added a commit to jKiler/oapi-codegen that referenced this issue Apr 8, 2024
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