export function adaptModel()

in packages/autorest.go/src/m4togocodemodel/types.ts [80:127]


export function adaptModel(obj: m4.ObjectSchema): go.ModelType | go.PolymorphicType {
  let modelType = types.get(obj.language.go!.name);
  if (modelType) {
    return <go.ModelType | go.PolymorphicType>modelType;
  }

  const annotations = new go.ModelAnnotations(obj.language.go!.omitSerDeMethods, false);
  if (obj.discriminator || obj.discriminatorValue) {
    let ifaceName: string | undefined;
    if (obj.language.go!.discriminatorInterface) {
      // only discriminators define the discriminatorInterface
      ifaceName = <string>obj.language.go!.discriminatorInterface;
    } else {
      // get it from the parent which must be a discriminator.
      // there are cases where a type might have multiple parents
      // so we iterate over them until we find the interface name
      // (e.g. KerberosKeytabCredentials type in machine learning)
      for (const parent of values( obj.parents?.immediate)) {
        if (parent.language.go!.discriminatorInterface) {
          ifaceName = <string>parent.language.go!.discriminatorInterface;
          break;
        }
      }
    }
    if (!ifaceName) {
      throw new Error(`failed to find discriminator interface name for type ${obj.language.go!.name}`);
    }
    const iface = types.get(ifaceName);
    if (!iface) {
      throw new Error(`didn't find InterfaceType for discriminator interface ${ifaceName} on type ${obj.language.go!.name}`);
    }
    modelType = new go.PolymorphicType(obj.language.go!.name, <go.InterfaceType>iface, annotations, adaptUsage(obj));
    // only non-root and sub-root discriminators will have a discriminatorValue
    if (obj.discriminatorValue) {
      (<go.PolymorphicType>modelType).discriminatorValue = getDiscriminatorLiteral(obj.discriminatorValue);
    }
  } else {
    modelType = new go.ModelType(obj.language.go!.name, annotations, adaptUsage(obj));
    // polymorphic types don't have XMLInfo
    modelType.xml = adaptXMLInfo(obj);
  }
  if (hasDescription(obj.language.go!)) {
    modelType.docs.description = obj.language.go!.description;
  }

  types.set(obj.language.go!.name, modelType);
  return modelType;
}