Openapi-generator: ReferenceError: FormData is not defined, if run at nodejs without browser.

Created on 20 May 2019  路  11Comments  路  Source: OpenAPITools/openapi-generator

https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator/src/main/resources/typescript-axios/apiInner.mustache
code line 55

const localVarFormParams = new {{^multipartFormData}}URLSearchParams(){{/multipartFormData}}{{#multipartFormData}}FormData(){{/multipartFormData}};{{/hasFormParams}}{{/vendorExtensions}}

will compiled with

const localVarFormParams = new FormData();

but FormData is unavailable at nodejs runtime.

Bug

Most helpful comment

@Bessonov you are invited to apply to fix to the typescript-fetch generator as well.

All 11 comments

The referenced issue above does not fix this bug. It is not a misconfigured tsconfig.ts issue.

This is the error with 'form-data' imported to the global scope.

runtime.js:83
                body: requestOpts.body instanceof FormData ? requestOpts.body : JSON.stringify(requestOpts.body),
                                       ^

TypeError: Right-hand side of 'instanceof' is not callable

This is the error with an import directly in the runtime.ts file.

runtime.ts:111:47 - error TS2359: The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.

111             body: requestOpts.body instanceof FormData ? requestOpts.body : JSON.stringify(requestOpts.body),

I'm not sure where to go from here to make typescript-rxjs node compatible.

Edit: I'm considering forking the project and maintaining my own resource template. I'm hesitant of issuing a pull to the existing community source code when I don't quite understand how typescript-rxjs works as a web client.

Any contribution here is appreciated.
Any could be added to the instanceof expression

Everything in the generated file is for a browser environment as it seems (uses window and much more).

I'm personally using the generated openapi client for server-side testing only.
In my case, simply defining a dummy global.FormData property was enough to avoid instanceof FormData throwing (and always returning false).

// Mock for open API tests
((global as unknown) as { FormData: unknown }).FormData = class FormData {}; // or jest.fn()

If you actually need to use FormData, I'd suggest using something like this instead of an empty class.

Polluting the global object should definitely work, but I wanted something where I don't have to rely on it so came up with this:
https://github.com/OpenAPITools/openapi-generator/pull/7455
Feedback would be most welcome.

What's about typescript-fetch?

@Bessonov you are invited to apply to fix to the typescript-fetch generator as well.

Was this page helpful?
0 / 5 - 0 ratings