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

NSwag Typescript generation not creating unions for known return types #5094

Open
ctigrisht opened this issue Jan 26, 2025 · 0 comments
Open

Comments

@ctigrisht
Copy link

Hello,

I've got a route that returns multiple types, shown below; It is clear that there are different types being returned, however the beginLogin RPC is only shown to return a single type: BeginLoginResponse. In fact, the 204 response is being treated as an error by the processor.

I've put my configuration below:

{
  "runtime": "Net90",
  "defaultVariables": null,
  "documentGenerator": {
    "aspNetCoreToOpenApi": {
      "project": "../ApiServerNode/ApiServerNode.csproj",
      "documentName": "v1",
      "msBuildProjectExtensionsPath": null,
      "configuration": null,
      "runtime": null,
      "targetFramework": null,
      "noBuild": false,
      "msBuildOutputPath": null,
      "verbose": true,
      "workingDirectory": null,
      "aspNetCoreEnvironment": null,
      "output": null,
      "newLineBehavior": "Auto"
    }
  },
  "codeGenerators": {
    "openApiToTypeScriptClient": {
      "className": "{controller}Client",
      "moduleName": "",
      "namespace": "",
      "typeScriptVersion": 2.7,
      "template": "Fetch",
      "promiseType": "Promise",
      "httpClass": "HttpClient",
      "withCredentials": false,
      "useSingletonProvider": false,
      "injectionTokenType": "OpaqueToken",
      "rxJsVersion": 6.0,
      "dateTimeType": "Date",
      "nullValue": "Undefined",
      "generateClientClasses": true,
      "generateClientInterfaces": false,
      "generateOptionalParameters": false,
      "exportTypes": true,
      "wrapDtoExceptions": false,
      "exceptionClass": "ApiException",
      "clientBaseClass": null,
      "wrapResponses": true,
      "wrapResponseMethods": [],
      "generateResponseClasses": true,
      "responseClass": "SwaggerResponse",
      "protectedMethods": [],
      "configurationClass": null,
      "useTransformOptionsMethod": false,
      "useTransformResultMethod": false,
      "generateDtoTypes": true,
      "operationGenerationMode": "MultipleClientsFromOperationId",
      "markOptionalProperties": true,
      "generateCloneMethod": false,
      "typeStyle": "Class",
      "enumStyle": "Enum",
      "useLeafType": false,
      "classTypes": [],
      "extendedClasses": [],
      "extensionCode": null,
      "generateDefaultValues": true,
      "excludedTypeNames": [],
      "excludedParameterNames": [],
      "handleReferences": false,
      "generateTypeCheckFunctions": false,
      "generateConstructorInterface": true,
      "convertConstructorInterfaceData": false,
      "importRequiredTypes": true,
      "useGetBaseUrlMethod": false,
      "baseUrlTokenName": "API_BASE_URL",
      "queryNullValue": "",
      "useAbortSignal": false,
      "inlineNamedDictionaries": false,
      "inlineNamedAny": false,
      "includeHttpContext": false,
      "templateDirectory": null,
      "serviceHost": null,
      "serviceSchemes": null,
      "output": "services/rpcs.ts",
      "newLineBehavior": "Auto"
    }
  }
}
        builder.Services.AddOpenApiDocument(x =>
        {
            x.OperationProcessors.Add(new OperationProcessor(ctx =>
            {
                ctx.OperationDescription.Operation.Parameters.Add(new OpenApiHeader
                {
                    Name = "Authorization",
                    Type = NJsonSchema.JsonObjectType.Object,
                    Kind = OpenApiParameterKind.Header,
                    IsRequired = false,
                    Description = "Server authorization token"
                });

                return true;
            }));
        });
[HttpPost("BeginLogin")]
    [ProducesResponseType(typeof(AppError), 400)]
    [ProducesResponseType(typeof(BeginLoginResponse), 200)]
    [ProducesResponseType(typeof(CompleteLoginResponse), 204)]
    public async Task<IActionResult> BeginLogin([FromBody] BeginLoginRequest request)
    beginLogin(authorization: any | undefined, request: BeginLoginRequest): Promise<SwaggerResponse<BeginLoginResponse>> {
        let url_ = this.baseUrl + "/v1/Authentication/BeginLogin";
        url_ = url_.replace(/[?&]$/, "");

        const content_ = JSON.stringify(request);

        let options_: RequestInit = {
            body: content_,
            method: "POST",
            headers: {
                "Authorization": authorization !== undefined && authorization !== null ? "" + authorization : "",
                "Content-Type": "application/json",
                "Accept": "application/json"
            }
        };

        return this.http.fetch(url_, options_).then((_response: Response) => {
            return this.processBeginLogin(_response);
        });
    }

    protected processBeginLogin(response: Response): Promise<SwaggerResponse<BeginLoginResponse>> {
        const status = response.status;
        let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
        if (status === 400) {
            return response.text().then((_responseText) => {
            let result400: any = null;
            let resultData400 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
            result400 = AppError.fromJS(resultData400);
            return throwException("A server side error occurred.", status, _responseText, _headers, result400);
            });
        } else if (status === 200) {
            return response.text().then((_responseText) => {
            let result200: any = null;
            let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
            result200 = BeginLoginResponse.fromJS(resultData200);
            return new SwaggerResponse(status, _headers, result200);
            });
        } else if (status === 204) {
            return response.text().then((_responseText) => {
            let result204: any = null;
            let resultData204 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
            result204 = CompleteLoginResponse.fromJS(resultData204);
            return throwException("A server side error occurred.", status, _responseText, _headers, result204);
            });
        } else if (status !== 200 && status !== 204) {
            return response.text().then((_responseText) => {
            return throwException("An unexpected server error occurred.", status, _responseText, _headers);
            });
        }
        return Promise.resolve<SwaggerResponse<BeginLoginResponse>>(new SwaggerResponse(status, _headers, null as any));
    }
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