-
-
Notifications
You must be signed in to change notification settings - Fork 435
Add ky HTTP client support #1802
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
torrespro
wants to merge
3
commits into
acacode:main
Choose a base branch
from
torrespro:add-ky-http-client
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| --- | ||
| "swagger-typescript-api": minor | ||
| --- | ||
|
|
||
| Add ky HTTP client support | ||
|
|
||
| The `--http-client ky` CLI flag and `httpClientType: "ky"` library option now generate an API client backed by [ky](https://github.com/sindresorhus/ky), a tiny fetch-based HTTP client with retries and a cleaner API. | ||
|
|
||
| The generated ky client reuses the same `HttpResponse<D, E>` response wrapper, `ResponseFormat`, query serialization, `secure`/`securityWorker`, `cancelToken`, `unwrapResponseData`, and `disableThrowOnError` semantics. ky's default timeout (10 s) and retry behavior are both disabled so the generated client behaves like the Fetch client out of the box; users can re-enable them via `ApiConfig.baseApiParams`. Users only need to install `ky` as a dependency in their project. | ||
|
|
||
| Also fixes a CLI bug where any truthy `--http-client` value was silently coerced to `axios` instead of being honored. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,267 @@ | ||
| <% | ||
| const { apiConfig, generateResponses, config } = it; | ||
| const CT = includeFile("@base/content-type-accessors", { config }); | ||
| %> | ||
| import ky from "ky"; | ||
| import type { KyInstance } from "ky"; | ||
|
|
||
| export type QueryParamsType = Record<string | number, any>; | ||
| export type ResponseFormat = keyof Omit<Body, "body" | "bodyUsed">; | ||
|
|
||
| export interface FullRequestParams extends Omit<RequestInit, "body"> { | ||
| /** set parameter to `true` for call `securityWorker` for this request */ | ||
| secure?: boolean; | ||
| /** request path */ | ||
| path: string; | ||
| /** content type of request body */ | ||
| type?: ContentType; | ||
| /** query params */ | ||
| query?: QueryParamsType; | ||
| /** format of response (i.e. response.json() -> format: "json") */ | ||
| format?: ResponseFormat; | ||
| /** request body */ | ||
| body?: unknown; | ||
| /** base url */ | ||
| baseUrl?: string; | ||
| /** request cancellation token */ | ||
| cancelToken?: CancelToken; | ||
| } | ||
|
|
||
| export type RequestParams = Omit<FullRequestParams, "body" | "method" | "query" | "path"> | ||
|
|
||
|
|
||
| export interface ApiConfig<SecurityDataType = unknown> { | ||
| baseUrl?: string; | ||
| baseApiParams?: Omit<RequestParams, "baseUrl" | "cancelToken" | "signal">; | ||
| securityWorker?: (securityData: SecurityDataType | null) => Promise<RequestParams | void> | RequestParams | void; | ||
| customFetch?: typeof fetch; | ||
| } | ||
|
|
||
| export interface HttpResponse<D extends unknown, E extends unknown = unknown> extends Response { | ||
| data: D; | ||
| error: E; | ||
| } | ||
|
|
||
| type CancelToken = Symbol | string | number; | ||
|
|
||
| <% if (config.enumStyle === "const") { %> | ||
| export const ContentType = { | ||
| Json: "application/json", | ||
| JsonApi: "application/vnd.api+json", | ||
| FormData: "multipart/form-data", | ||
| UrlEncoded: "application/x-www-form-urlencoded", | ||
| Text: "text/plain", | ||
| } as const; | ||
| export type ContentType = (typeof ContentType)[keyof typeof ContentType]; | ||
| <% } else if (config.enumStyle === "union") { %> | ||
| export type ContentType = "application/json" | "application/vnd.api+json" | "multipart/form-data" | "application/x-www-form-urlencoded" | "text/plain"; | ||
| <% } else if (config.enumStyle === "const-enum") { %> | ||
| export const enum ContentType { | ||
| Json = "application/json", | ||
| JsonApi = "application/vnd.api+json", | ||
| FormData = "multipart/form-data", | ||
| UrlEncoded = "application/x-www-form-urlencoded", | ||
| Text = "text/plain", | ||
| } | ||
| <% } else { %> | ||
| export enum ContentType { | ||
| Json = "application/json", | ||
| JsonApi = "application/vnd.api+json", | ||
| FormData = "multipart/form-data", | ||
| UrlEncoded = "application/x-www-form-urlencoded", | ||
| Text = "text/plain", | ||
| } | ||
| <% } %> | ||
|
|
||
| export class HttpClient<SecurityDataType = unknown> { | ||
| public baseUrl: string = "<%~ apiConfig.baseUrl %>"; | ||
| private securityData: SecurityDataType | null = null; | ||
| private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"]; | ||
| private abortControllers = new Map<CancelToken, AbortController>(); | ||
| private customFetch?: typeof fetch; | ||
| private instance: KyInstance; | ||
|
|
||
| private baseApiParams: RequestParams = { | ||
| credentials: 'same-origin', | ||
| headers: {}, | ||
| redirect: 'follow', | ||
| referrerPolicy: 'no-referrer', | ||
| } | ||
|
|
||
| constructor(apiConfig: ApiConfig<SecurityDataType> = {}) { | ||
| Object.assign(this, apiConfig); | ||
| // ky wraps fetch; use the caller-supplied fetch if provided, otherwise the global. | ||
| // throwHttpErrors: false — we handle non-2xx ourselves to match fetch behavior. | ||
| // timeout: false — fetch has no built-in timeout; disable ky's default 10 s limit. | ||
| // retry: 0 — fetch does not retry; disable ky's default retry behavior. | ||
| this.instance = ky.create({ | ||
| fetch: this.customFetch ?? fetch, | ||
| throwHttpErrors: false, | ||
| timeout: false, | ||
| retry: 0, | ||
| }); | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
|
||
| } | ||
|
|
||
| public setSecurityData = (data: SecurityDataType | null) => { | ||
| this.securityData = data; | ||
| } | ||
|
|
||
| protected encodeQueryParam(key: string, value: any) { | ||
| const encodedKey = encodeURIComponent(key); | ||
| return `${encodedKey}=${encodeURIComponent(typeof value === "number" ? value : `${value}`)}`; | ||
| } | ||
|
|
||
| protected addQueryParam(query: QueryParamsType, key: string) { | ||
| return this.encodeQueryParam(key, query[key]); | ||
| } | ||
|
|
||
| protected addArrayQueryParam(query: QueryParamsType, key: string) { | ||
| const value = query[key]; | ||
| return value.map((v: any) => this.encodeQueryParam(key, v)).join("&"); | ||
| } | ||
|
|
||
| protected toQueryString(rawQuery?: QueryParamsType): string { | ||
| const query = rawQuery || {}; | ||
| const keys = Object.keys(query).filter((key) => "undefined" !== typeof query[key]); | ||
| return keys | ||
| .map((key) => | ||
| Array.isArray(query[key]) | ||
| ? this.addArrayQueryParam(query, key) | ||
| : this.addQueryParam(query, key), | ||
| ) | ||
| .join("&"); | ||
| } | ||
|
|
||
| protected addQueryParams(rawQuery?: QueryParamsType): string { | ||
| const queryString = this.toQueryString(rawQuery); | ||
| return queryString ? `?${queryString}` : ""; | ||
| } | ||
|
|
||
| private contentFormatters: Record<ContentType, (input: any) => any> = { | ||
| [<%~ CT.Json %>]: (input:any) => input !== null && (typeof input === "object" || typeof input === "string") ? JSON.stringify(input) : input, | ||
| [<%~ CT.JsonApi %>]: (input:any) => input !== null && (typeof input === "object" || typeof input === "string") ? JSON.stringify(input) : input, | ||
| [<%~ CT.Text %>]: (input:any) => input !== null && typeof input !== "string" ? JSON.stringify(input) : input, | ||
| [<%~ CT.FormData %>]: (input: any) => { | ||
| if (input instanceof FormData) { | ||
| return input; | ||
| } | ||
|
|
||
| return Object.keys(input || {}).reduce((formData, key) => { | ||
| const property = input[key]; | ||
| formData.append( | ||
| key, | ||
| property instanceof Blob ? | ||
| property : | ||
| typeof property === "object" && property !== null ? | ||
| JSON.stringify(property) : | ||
| `${property}` | ||
| ); | ||
| return formData; | ||
| }, new FormData()); | ||
| }, | ||
| [<%~ CT.UrlEncoded %>]: (input: any) => this.toQueryString(input), | ||
| } | ||
|
|
||
| protected mergeRequestParams(params1: RequestParams, params2?: RequestParams): RequestParams { | ||
| return { | ||
| ...this.baseApiParams, | ||
| ...params1, | ||
| ...(params2 || {}), | ||
| headers: { | ||
| ...(this.baseApiParams.headers || {}), | ||
| ...(params1.headers || {}), | ||
| ...((params2 && params2.headers) || {}), | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| protected createAbortSignal = (cancelToken: CancelToken): AbortSignal | undefined => { | ||
| if (this.abortControllers.has(cancelToken)) { | ||
| const abortController = this.abortControllers.get(cancelToken); | ||
| if (abortController) { | ||
| return abortController.signal; | ||
| } | ||
| return void 0; | ||
| } | ||
|
|
||
| const abortController = new AbortController(); | ||
| this.abortControllers.set(cancelToken, abortController); | ||
| return abortController.signal; | ||
| } | ||
|
|
||
| public abortRequest = (cancelToken: CancelToken) => { | ||
| const abortController = this.abortControllers.get(cancelToken) | ||
|
|
||
| if (abortController) { | ||
| abortController.abort(); | ||
| this.abortControllers.delete(cancelToken); | ||
| } | ||
| } | ||
|
|
||
| public request = async <T = any, E = any>({ | ||
| body, | ||
| secure, | ||
| path, | ||
| type, | ||
| query, | ||
| format, | ||
| baseUrl, | ||
| cancelToken, | ||
| ...params | ||
| <% if (config.unwrapResponseData) { %> | ||
| }: FullRequestParams): Promise<T> => { | ||
| <% } else { %> | ||
| }: FullRequestParams): Promise<HttpResponse<T, E>> => { | ||
| <% } %> | ||
| const secureParams = ((typeof secure === 'boolean' ? secure : this.baseApiParams.secure) && this.securityWorker && await this.securityWorker(this.securityData)) || {}; | ||
| const requestParams = this.mergeRequestParams(params, secureParams); | ||
| const queryString = query && this.toQueryString(query); | ||
| const payloadFormatter = this.contentFormatters[type || <%~ CT.Json %>]; | ||
| const responseFormat = format || requestParams.format; | ||
|
|
||
| return this.instance( | ||
| `${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`, | ||
| { | ||
| ...requestParams, | ||
| headers: { | ||
| ...(requestParams.headers || {}), | ||
| ...(type && type !== <%~ CT.FormData %> ? { "Content-Type": type } : {}), | ||
| }, | ||
| signal: (cancelToken ? this.createAbortSignal(cancelToken) : requestParams.signal) || null, | ||
| body: typeof body === "undefined" || body === null ? null : payloadFormatter(body), | ||
| } | ||
| ).then(async (response) => { | ||
| const r = response as HttpResponse<T, E>; | ||
| r.data = (null as unknown) as T; | ||
| r.error = (null as unknown) as E; | ||
|
|
||
| const responseToParse = responseFormat ? response.clone() : response; | ||
| const data = !responseFormat ? r : await responseToParse[responseFormat]() | ||
| .then((data) => { | ||
| if (r.ok) { | ||
| r.data = data; | ||
| } else { | ||
| r.error = data; | ||
| } | ||
| return r; | ||
| }) | ||
| .catch((e) => { | ||
| r.error = e; | ||
| return r; | ||
| }); | ||
|
|
||
| <% if (!config.disableThrowOnError) { %> | ||
| if (!response.ok) throw data; | ||
| <% } %> | ||
| <% if (config.unwrapResponseData) { %> | ||
| return data.data; | ||
| <% } else { %> | ||
| return data; | ||
| <% } %> | ||
| }).finally(() => { | ||
| if (cancelToken) { | ||
| this.abortControllers.delete(cancelToken); | ||
| } | ||
| }); | ||
| }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.