Skip to content

Kubb ignores non-string or blob items in multipart/form-data #1876

@corentinbst

Description

@corentinbst

What version of kubb is running?

3.18.3

What kind of platform do you use?

Windows

Your kubb.config.ts config file?

Swagger/OpenAPI file?

What version of external packages are you using(@tanstack-query, MSW, React, Vue, ...)

What steps can reproduce the bug?

Using tanstack query and typescript. We're using multipart/form-data requests for file uploads, but they also contain various other items. For example:

/**
* Generated by Kubb (https://kubb.dev/).
* Do not edit manually.
*/


export type ImportRequest = {
    /**
     * @type string, binary
    */
    file: Blob;
    /**
     * @type object
    */
    bindings: {
        [key: string]: string;
    };
    /**
     * @description The line indexes to import. It starts at 1 for the first item (0 being the header). Can be null to (try to) import everything.
     * @type array
    */
    selectedLines?: number[] | null;
};

The issue is that Kubb simply ignores whatever non-string data there is when making the request, because of this code:

if (typeof value === 'string' || (value as unknown) instanceof Blob) {
       formData.append(key, value as unknown as string | Blob);
}

Full context:

/**
 * {@link /import}
 */
export async function _import(data: ImportMutationRequest, config: Partial<RequestConfig<ImportMutationRequest>> & { client?: typeof fetch } = {}) {
  const { client: request = fetch, ...requestConfig } = config  
  
  const requestData = data  
  const formData = new FormData()
  if (requestData) {
   Object.keys(requestData).forEach((key) => {
     const value = requestData[key as keyof typeof requestData];
     if (typeof value === 'string' || (value as unknown) instanceof Blob) {
       formData.append(key, value as unknown as string | Blob);
     }
   })
  }  
  const res = await request<ImportMutationResponse, ResponseErrorConfig<Import400 | Import401>, ImportMutationRequest>({ method : "POST", url : `/import`, data : formData, ... requestConfig, headers : { 'Content-Type': 'multipart/form-data', ...requestConfig.headers } })  
  return res.data
}

We're using an ASP .NET Core and after extensive testing, using JSON.stringify for non-string values works perfectly. Thus, this can be solved simply by changing the previous code to this:

if (typeof value === 'string' || (value as unknown) instanceof Blob) {
    formData.append(key, value as unknown as string | Blob);
} else {
    formData.append(key, JSON.stringify(value));
}

How often does this bug happen?

Every time

What is the expected behaviour?

No response

Additional information

No response

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions