autorest.typescript icon indicating copy to clipboard operation
autorest.typescript copied to clipboard

Mapped property for one member of result union not supported

Open xirzec opened this issue 1 year ago • 10 comments

We have an interesting case in OpenAI where one side of a result type had a mapped property, so the generated deserialization function didn't compile:

export async function _getAzureBatchImageGenerationOperationStatusDeserialize(
  result:
    | GetAzureBatchImageGenerationOperationStatus200Response
    | GetAzureBatchImageGenerationOperationStatusDefaultResponse
): Promise<BatchImageGenerationOperationResponse> {
  if (isUnexpected(result)) {
    throw result.body;
  }

  return {
    id: result.body["id"],
    created: result.body["created"],
    expires: result.body["expires"],
    result: !result.body.result
      ? undefined
      : {
          created: result.body.result?.["created"],
          data: result.body.result?.["data"],
        },
    status: result.body["status"],
    error: !result.body.error ? undefined : result.body.error,
  };
}

The problem is that in the case that result.body.result.data is a ImagePayload[], the wire property of b64_json needs to be converted to the friendly name of base64Data.

We worked around this for now by writing a manual conversion helper:

/**
 * Convert REST-level ImageGenerationsOutput.data to HLC-level ImageGenerations.data
 * @internal
 */
function toImageGenerationsData(
  input: ImageGenerationsOutput["data"]
): ImageLocation[] | ImagePayload[] {
  return input.map(function (locationOrPayload) {
    if ("url" in locationOrPayload) {
      return locationOrPayload as ImageLocation;
    } else {
      return {
        base64Data: locationOrPayload.b64_json,
      } as ImagePayload;
    }
  }) as ImageLocation[] | ImagePayload[];
}

This is a tricky problem to resolve since I think if the result was just one of these types we could unwind it and map it in a literal, but since it's a union we have to somehow generate code that only applies to the case where the property to be mapped exists.

xirzec avatar Jul 07 '23 19:07 xirzec