Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/add-ky-http-client.md
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.
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Swagger TypeScript API

- Support for OpenAPI 3.0, 2.0, JSON and YAML
- Generate the API Client for Fetch or Axios from an OpenAPI Specification
- Generate the API Client for Fetch, Axios, or ky from an OpenAPI Specification

Any questions you can ask here: <https://github.com/acacode/swagger-typescript-api/discussions>

Expand All @@ -19,6 +19,12 @@ You can use this package in two ways:
npx swagger-typescript-api generate --path ./swagger.json
```

To generate a `ky`-based client (install `ky` in your project first):

```bash
npx swagger-typescript-api generate --path ./swagger.json --http-client ky
```

Or install locally in your project:

```bash
Expand All @@ -38,8 +44,16 @@ import * as process from "node:process";
import { generateApi } from "swagger-typescript-api";

await generateApi({ input: path.resolve(process.cwd(), "./swagger.json") });

// Use ky as the HTTP client (install ky in your project first)
await generateApi({
input: path.resolve(process.cwd(), "./swagger.json"),
httpClientType: "ky",
});
```

The `httpClientType` option accepts `"fetch"` (default), `"axios"`, or `"ky"`. When using `"axios"` or `"ky"`, add the corresponding package as a dependency of the generated client's project.

For more detailed configuration options, please consult the documentation.

## Mass media
Expand Down
3 changes: 3 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 13 additions & 4 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,10 +342,19 @@ const generateCommand = defineCommand({
| "const"
| "const-enum"
| undefined,
httpClientType:
args["http-client"] || args.axios
? HTTP_CLIENT.AXIOS
: HTTP_CLIENT.FETCH,
httpClientType: (() => {
const raw = args["http-client"] as string | undefined;
const validValues = Object.values(HTTP_CLIENT) as string[];
if (raw) {
if (!validValues.includes(raw))
throw new Error(
`Invalid --http-client value "${raw}". Valid values: ${validValues.join(", ")}`,
);
return raw as HttpClientType;
}
if (args.axios) return HTTP_CLIENT.AXIOS;
return HTTP_CLIENT.FETCH;
})(),
input: path.resolve(process.cwd(), args.path as string),
modular: args.modular,
moduleNameFirstTag: args["module-name-first-tag"],
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
"@types/node": "26.0.0",
"@types/swagger2openapi": "7.0.4",
"axios": "1.18.0",
"ky": "^2.0.2",
"tsdown": "0.22.3",
"typedoc": "0.28.19",
"unrun": "^0.3.1",
Expand Down
1 change: 1 addition & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export const FILE_PREFIX = `/* eslint-disable */
export const HTTP_CLIENT = {
FETCH: "fetch",
AXIOS: "axios",
KY: "ky",
} as const;

export const PROJECT_VERSION = packageJson.version;
Expand Down
267 changes: 267 additions & 0 deletions templates/base/http-clients/ky-http-client.ejs
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,
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
timeout: false,
retry: 0,
});
Comment thread
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);
}
});
};
}
2 changes: 1 addition & 1 deletion templates/default/procedure-call.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const requestContentKind = includeFile("@base/content-type-accessors", { config
const responseContentKind = {
"JSON": '"json"',
"IMAGE": '"blob"',
"FORM_DATA": isFetchTemplate ? '"formData"' : '"document"'
"FORM_DATA": config.httpClientType !== HTTP_CLIENT.AXIOS ? '"formData"' : '"document"'
}

const bodyTmpl = _.get(payload, "name") || null;
Expand Down
2 changes: 1 addition & 1 deletion templates/modular/procedure-call.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const requestContentKind = includeFile("@base/content-type-accessors", { config
const responseContentKind = {
"JSON": '"json"',
"IMAGE": '"blob"',
"FORM_DATA": isFetchTemplate ? '"formData"' : '"document"'
"FORM_DATA": config.httpClientType !== HTTP_CLIENT.AXIOS ? '"formData"' : '"document"'
}

const bodyTmpl = _.get(payload, "name") || null;
Expand Down
Loading