Skip to content

Use discriminator with several mappings for one schema #1530

Closed

Description

@maks56893

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
			}
		}

Activity

  1. added 3 commits that reference this issue on Apr 8, 2024
    1ca6895
    9f2f773
    605d9e3
  2. mgabeler-lee-6rs commented on Oct 2, 2024

    @mgabeler-lee-6rs
    Contributor

    Having this same issue, also finding that the generated code in this case is non-deterministic which adds extra pain for CI stesp trying to ensure that the generated code is up to date

  3. benazir-sba commented on Jan 17, 2025

    @benazir-sba

    Having the same issue. Would love to see it solved 🗡

  4. gerhardwagner commented on Jan 17, 2025

    @gerhardwagner

    can we see a PR and a merge of this ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions