Giter VIP home page Giter VIP logo

Comments (3)

stijnvanhulle avatar stijnvanhulle commented on June 20, 2024

Kubb version 2.13.3 will resolve this.

from kubb.

ghingis avatar ghingis commented on June 20, 2024

@stijnvanhulle
I just tried it with version 2.16.3 and the aforementioned issue still persists.

this is the generated hook for the openapi spec above:

import client from "@kubb/swagger-client/client";
import { useMutation } from "@tanstack/react-query";
import type { UploadFileMutationRequest, UploadFileMutationResponse, UploadFile400 } from "../types/UploadFile";
import type { UseMutationOptions, UseMutationResult } from "@tanstack/react-query";

 type UploadFileClient = typeof client<UploadFileMutationResponse, UploadFile400, UploadFileMutationRequest>;
type UploadFile = {
    data: UploadFileMutationResponse;
    error: UploadFile400;
    request: UploadFileMutationRequest;
    pathParams: never;
    queryParams: never;
    headerParams: never;
    response: UploadFileMutationResponse;
    client: {
        parameters: Partial<Parameters<UploadFileClient>[0]>;
        return: Awaited<ReturnType<UploadFileClient>>;
    };
};
/**
 * @description Upload file
 * @link /api/v1/upload
 */
export function useUploadFile(options: {
    mutation?: UseMutationOptions<UploadFile["response"], UploadFile["error"], {
        data: UploadFile["request"];
    }>;
    client?: UploadFile["client"]["parameters"];
} = {}): UseMutationResult<UploadFile["response"], UploadFile["error"], {
    data: UploadFile["request"];
}> {
    const { mutation: mutationOptions, client: clientOptions = {} } = options ?? {};
    return useMutation<UploadFile["response"], UploadFile["error"], {
        data: UploadFile["request"];
    }>({
        mutationFn: async ({ data }) => {
            const res = await client<UploadFile["data"], UploadFile["error"], UploadFile["request"]>({
                method: "post",
                url: `/api/v1/upload`,
                data,
                ...clientOptions
            });
            return res.data;
        },
        ...mutationOptions
    });
}

As you can see the header is missing, so does the param conversion to form data.

I can see that the generated type is now a Blob as expected:

 export type UploadFileMutationRequest = {
    /**
     * @type string, binary
    */
    file: Blob;
}; 

from kubb.

ghingis avatar ghingis commented on June 20, 2024

I'm not yet familiar with the code, but it seems this is the template that should change:

function Template({ name, generics, returnType, params, mutateParams, JSDoc, client, hook, dataReturnType }: TemplateProps): ReactNode {
const isV5 = new PackageManager().isValidSync(/@tanstack/, '>=5')
const clientOptions = [
`method: "${client.method}"`,
`url: ${client.path.template}`,
client.withQueryParams ? 'params' : undefined,
client.withData ? 'data' : undefined,
client.withHeaders ? 'headers: { ...headers, ...clientOptions.headers }' : undefined,
'...clientOptions',
].filter(Boolean)
const resolvedClientOptions = `${transformers.createIndent(4)}${clientOptions.join(`,\n${transformers.createIndent(4)}`)}`
if (isV5) {
return (
<Function export name={name} params={params} JSDoc={JSDoc}>
{`
const { mutation: mutationOptions, client: clientOptions = {} } = options ?? {}
return ${hook.name}({
mutationFn: async(${mutateParams}) => {
${hook.children || ''}
const res = await client<${client.generics}>({
${resolvedClientOptions}
})
return ${dataReturnType === 'data' ? 'res.data' : 'res'}
},
...mutationOptions
})`}
</Function>
)
}
return (
<Function export name={name} generics={generics} returnType={returnType} params={params} JSDoc={JSDoc}>
{`
const { mutation: mutationOptions, client: clientOptions = {} } = options ?? {}
return ${hook.name}<${hook.generics}>({
mutationFn: async(${mutateParams}) => {
${hook.children || ''}
const res = await client<${client.generics}>({
${resolvedClientOptions}
})
return ${dataReturnType === 'data' ? 'res.data' : 'res'}
},
...mutationOptions
})`}
</Function>
)
}

To something like this:

function Template({ name, generics, returnType, params, mutateParams, JSDoc, client, hook, dataReturnType }: TemplateProps): ReactNode {
  const isV5 = new PackageManager().isValidSync(/@tanstack/, '>=5')
  const operation = useOperation()
  const { getSchemas } = useOperationManager()
  const schemas = getSchemas(operation);
  const dataTransform = [];

  if (!('application/json' in schemas.request?.operation?.schema?.requestBody?.content)){
    const acceptedHeaders = Object.keys(schemas.request?.operation?.schema?.requestBody?.content);
    if (acceptedHeaders.includes('multipart/form-data')){
      dataTransform.push(`
      const transformedData = new FormData();
      transformedData.append('file', data.file);
      `);
    } else {
      // some kind of log that lets the developer know that we does not support the request header type application/json by default
      // ad just send the data as is
    }
  }

  const clientOptions = [
    `method: "${client.method}"`,
    `url: ${client.path.template}`,
    client.withQueryParams ? 'params' : undefined,
    client.withData ? dataTransform.length > 0 ? 'data: transformedData' : 'data' : undefined,
    client.withHeaders ? 'headers: { ...headers, ...clientOptions.headers }' : undefined,
    '...clientOptions',
  ].filter(Boolean)

  const resolvedClientOptions = `${transformers.createIndent(4)}${clientOptions.join(`,\n${transformers.createIndent(4)}`)}`

  if (isV5) {
    return (
      <Function export name={name} params={params} JSDoc={JSDoc}>
        {`
         const { mutation: mutationOptions, client: clientOptions = {} } = options ?? {}

         return ${hook.name}({
           mutationFn: async(${mutateParams}) => {
            ${dataTransform ? dataTransform.join('\n') : null}
            ${hook.children || ''}
             const res = await client<${client.generics}>({
              ${resolvedClientOptions}
             })

             return ${dataReturnType === 'data' ? 'res.data' : 'res'}
           },
           ...mutationOptions
         })`}
      </Function>
    )
  }

  return (
    <Function export name={name} generics={generics} returnType={returnType} params={params} JSDoc={JSDoc}>
      {`
       const { mutation: mutationOptions, client: clientOptions = {} } = options ?? {}

       return ${hook.name}<${hook.generics}>({
         mutationFn: async(${mutateParams}) => {
          ${dataTransform ? dataTransform.join('\n') : null}
          ${hook.children || ''}
           const res = await client<${client.generics}>({
            ${resolvedClientOptions}
           })

           return ${dataReturnType === 'data' ? 'res.data' : 'res'}
         },
         ...mutationOptions
       })`}
    </Function>
  )
}      

from kubb.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.