|
| 1 | +# Custom request file |
| 2 | + |
| 3 | +If you want to implement custom logic on the request level, |
| 4 | +or implement a client based on a different library, then |
| 5 | +one option is to write your own request file and tell |
| 6 | +the generator to use this. |
| 7 | + |
| 8 | +The request file (`request.ts`) can be found inside the |
| 9 | +`/core` folder of the generated client. You can modify |
| 10 | +that file and use it, or alternatively, you can write |
| 11 | +your own. Below is a very simplified example of an Axios |
| 12 | +based request file: |
| 13 | + |
| 14 | +```typescript |
| 15 | +import axios from 'axios'; |
| 16 | +import type { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios'; |
| 17 | + |
| 18 | +import type { ApiRequestOptions } from './ApiRequestOptions'; |
| 19 | +import { CancelablePromise } from './CancelablePromise'; |
| 20 | +import type { OpenAPIConfig } from './OpenAPI'; |
| 21 | + |
| 22 | +const axiosInstance = axios.create({ |
| 23 | + // Your custom Axios instance config |
| 24 | +}); |
| 25 | + |
| 26 | +export const request = <T>(config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise<T> => { |
| 27 | + return new CancelablePromise((resolve, reject, onCancel) => { |
| 28 | + // Get the request URL. Depending on your needs, this might need additional processing, |
| 29 | + // @see ./src/templates/core/functions/getUrl.hbs |
| 30 | + const url = `${config.BASE}${options.path}`; |
| 31 | + |
| 32 | + // Optional: Get and link the cancelation token, so the request can be aborted. |
| 33 | + const source = axiosInstance.CancelToken.source(); |
| 34 | + onCancel(() => source.cancel('The user aborted a request.')); |
| 35 | + |
| 36 | + // Execute the request. This is a minimal example, in real world scenarios |
| 37 | + // you will need to add headers, process form data, etc. |
| 38 | + // @see ./src/templates/core/axios/request.hbs |
| 39 | + axiosInstance.request({ |
| 40 | + url, |
| 41 | + data: options.body, |
| 42 | + method: options.method, |
| 43 | + cancelToken: source.token, |
| 44 | + }).then(data => { |
| 45 | + resolve(data); |
| 46 | + }).catch(error => { |
| 47 | + reject(error); |
| 48 | + }); |
| 49 | + }); |
| 50 | +}; |
| 51 | +``` |
| 52 | + |
| 53 | +To use this request file in your generated code you can execute the |
| 54 | +following command: |
| 55 | + |
| 56 | +``` |
| 57 | +npx openapi-typescript-codegen --input ./spec.json --output ./generated --request ./request.ts |
| 58 | +``` |
| 59 | + |
| 60 | +The `--request` parameter will tell the generator to not generate the default |
| 61 | +`request.ts` file, but instead copy over the custom file that was specified. |
0 commit comments