openapi-typescript-codegen icon indicating copy to clipboard operation
openapi-typescript-codegen copied to clipboard

Is there a example of multipart/form-data request?

Open dim0627 opened this issue 3 years ago • 6 comments

Thanks for so awesome library! I'm using openapi-typescript-codegen so many projects.

I have in trouble. I wanna use in React Native project for image file upload usecase with expo-image-picker. But I couldn't implements this with FormData pattern and Blob pattern. Is there an example of multipart/form-data request?

dim0627 avatar Mar 30 '22 12:03 dim0627

Hi,

I had the same issue. Using this in a React Native project and POSTing with FormData.

There is a bug in the codegen tool.

I have managed to get this to work in the end.

  1. Issue with default export in request.js
const getFormData = (options) => {
    if (options.formData) {
        //const formData = new form_data_1.default(); // <-- Had to change this
        const formData = new form_data_1(); // <-- To this
        return formData;
    }
    return undefined;
};
  1. Issue with request.js in getHeaders()

This test do not check options.formData if it is set so the request do not have any data.

...
    if (options.body) {
        if (options.mediaType) {
            headers['Content-Type'] = options.mediaType;
        }
        else if (isBlob(options.body)) {
            headers['Content-Type'] = options.body.type || 'application/octet-stream';
        }
        else if (isString(options.body)) {
            headers['Content-Type'] = 'text/plain';
        }
        else if (!isFormData(options.body)) {
            headers['Content-Type'] = 'application/json';
        }
    }
...

This is due to the generated code:

    static postUpload(formData) {
        return (0, request_1.request)(OpenAPI_1.OpenAPI, {
            method: 'POST',
            url: '/Upload',
            formData: formData, // <-- Will not work due to the test above
            mediaType: 'multipart/form-data'
        });

A workaround here is to do this by setting the body:

    static postUpload(formData) {
        return (0, request_1.request)(OpenAPI_1.OpenAPI, {
            method: 'POST',
            url: '/Upload',
            body: formData, // <-- Passing as body due to the test described above
            mediaType: 'multipart/form-data'
        });

PS: If you use the body insted of formData the issue in pt. 1 will also never happen.

I hope this help both you and the devs. :)

snap608 avatar Jun 10 '22 11:06 snap608

Yep, this happens to me too, hope a fix can be merged soon

JSH32 avatar Jun 19 '22 02:06 JSH32