Skip to content
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

feat: add --ky option #690

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
3 changes: 2 additions & 1 deletion README.md
Expand Up @@ -68,6 +68,7 @@ Options:
--disableStrictSSL disabled strict SSL (default: false)
--disableProxy disabled proxy (default: false)
--axios generate axios http client (default: false)
--ky generate ky http client (default: false)
--unwrap-response-data unwrap the data item from the response (default: false)
--disable-throw-on-error Do not throw an error when response.ok is not true (default: false)
--single-http-client Ability to send HttpClient instance to Api constructor (default: false)
Expand Down Expand Up @@ -124,7 +125,7 @@ generateApi({
// ...
},
templates: path.resolve(process.cwd(), './api-templates'),
httpClientType: "axios", // or "fetch"
httpClientType: "axios", // or "fetch" or "ky"
defaultResponseAsSuccess: false,
generateClient: true,
generateRouteTypes: false,
Expand Down
7 changes: 6 additions & 1 deletion index.js
Expand Up @@ -162,6 +162,11 @@ const program = cli({
description: 'generate axios http client',
default: codeGenBaseConfig.httpClientType === HTTP_CLIENT.AXIOS,
},
{
flags: '--ky',
description: 'generate axios http client',
default: codeGenBaseConfig.httpClientType === HTTP_CLIENT.KY,
},
{
flags: '--unwrap-response-data',
description: 'unwrap the data item from the response',
Expand Down Expand Up @@ -324,7 +329,7 @@ const main = async () => {
url: options.path,
generateRouteTypes: options.routeTypes,
generateClient: !!(options.axios || options.client),
httpClientType: options.axios ? HTTP_CLIENT.AXIOS : HTTP_CLIENT.FETCH,
httpClientType: options.axios ? HTTP_CLIENT.AXIOS : options.ky ? HTTP_CLIENT.KY : HTTP_CLIENT.FETCH,
input: resolve(process.cwd(), options.path),
output: resolve(process.cwd(), options.output || '.'),
...customConfig,
Expand Down
1 change: 1 addition & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Expand Up @@ -85,6 +85,7 @@
"dotenv": "^16.3.1",
"git-diff": "^2.0.6",
"husky": "^8.0.3",
"ky": "^1.2.2",
"pretty-quick": "^3.1.3",
"rimraf": "^5.0.1"
},
Expand Down
1 change: 1 addition & 0 deletions src/constants.js
Expand Up @@ -28,6 +28,7 @@ const SCHEMA_TYPES = {
const HTTP_CLIENT = {
FETCH: 'fetch',
AXIOS: 'axios',
KY: 'ky',
};

const PROJECT_VERSION = packageJson.version;
Expand Down
220 changes: 220 additions & 0 deletions templates/base/http-clients/ky-http-client.ejs
@@ -0,0 +1,220 @@
<%
const { apiConfig, generateResponses, config } = it;
%>

import type {
BeforeRequestHook,
Hooks,
KyInstance,
Options as KyOptions,
NormalizedOptions,
SearchParamsOption,
} from "ky";
import ky from "ky";

type KyResponse<Data> = Response & {
json<T extends Data = Data>(): Promise<T>;
}

export type ResponsePromise<Data> = {
arrayBuffer: () => Promise<ArrayBuffer>;
blob: () => Promise<Blob>;
formData: () => Promise<FormData>;
json<T extends Data = Data>(): Promise<T>;
text: () => Promise<string>;
} & Promise<KyResponse<Data>>;

export type ResponseFormat = keyof Omit<Body, "body" | "bodyUsed">;

export interface FullRequestParams
extends Omit<KyOptions, "json" | "body" | "searchParams"> {
/** 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?: SearchParamsOption;
/** format of response (i.e. response.json() -> format: "json") */
format?: ResponseFormat;
/** request body */
body?: unknown;
}

export type RequestParams = Omit<
FullRequestParams,
"body" | "method" | "query" | "path"
>;

export interface ApiConfig<SecurityDataType = unknown>
extends Omit<KyOptions, "data" | "cancelToken"> {
securityWorker?: (
securityData: SecurityDataType | null,
) => Promise<NormalizedOptions | void> | NormalizedOptions | void;
secure?: boolean;
format?: ResponseType;
}

export enum ContentType {
Json = "application/json",
FormData = "multipart/form-data",
UrlEncoded = "application/x-www-form-urlencoded",
Text = "text/plain",
}

export class HttpClient<SecurityDataType = unknown> {
public ky: KyInstance;
private securityData: SecurityDataType | null = null;
private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"];
private secure?: boolean;
private format?: ResponseType;

constructor({
securityWorker,
secure,
format,
...options
}: ApiConfig<SecurityDataType> = {}) {
this.ky = ky.create({ ...options, prefixUrl: options.prefixUrl || "" });
this.secure = secure;
this.format = format;
this.securityWorker = securityWorker;
}

public setSecurityData = (data: SecurityDataType | null) => {
this.securityData = data;
};

protected mergeRequestParams(
params1: KyOptions,
params2?: KyOptions,
): KyOptions {
return {
...params1,
...params2,
headers: {
...params1.headers,
...(params2 && params2.headers),
},
};
}

protected stringifyFormItem(formItem: unknown) {
if (typeof formItem === "object" && formItem !== null) {
return JSON.stringify(formItem);
} else {
return `${formItem}`;
}
}

protected createFormData(input: Record<string, unknown>): FormData {
return Object.keys(input || {}).reduce((formData, key) => {
const property = input[key];
const propertyContent: any[] =
property instanceof Array ? property : [property];

for (const formItem of propertyContent) {
const isFileType = formItem instanceof Blob || formItem instanceof File;
formData.append(
key,
isFileType ? formItem : this.stringifyFormItem(formItem),
);
}

return formData;
}, new FormData());
}

public request = <T = any, _E = any>({
secure = this.secure,
path,
type,
query,
format,
body,
...options
<% if (config.unwrapResponseData) { %>
}: FullRequestParams): Promise<T> => {
<% } else { %>
}: FullRequestParams): ResponsePromise<T> => {
<% } %>
if (body) {
if (type === ContentType.FormData) {
body =
typeof body === "object"
? this.createFormData(body as Record<string, unknown>)
: body;
} else if (type === ContentType.Text) {
body = typeof body !== "string" ? JSON.stringify(body) : body;
}
}

let headers: Headers | Record<string, string | undefined> | undefined;
if (options.headers instanceof Headers) {
headers = new Headers(options.headers);
if (type && type !== ContentType.FormData) {
headers.set("Content-Type", type);
}
} else {
headers = { ...options.headers } as Record<string, string | undefined>;
if (type && type !== ContentType.FormData) {
headers["Content-Type"] = type;
}
}

let hooks: Hooks | undefined;
if (secure && this.securityWorker) {
const securityWorker: BeforeRequestHook = async (request, options) => {
const secureOptions = await this.securityWorker!(this.securityData);
if (secureOptions && typeof secureOptions === "object") {
let { headers } = options;
if (secureOptions.headers) {
const mergedHeaders = new Headers(headers);
const secureHeaders = new Headers(secureOptions.headers);
secureHeaders.forEach((value, key) => {
mergedHeaders.set(key, value);
});
headers = mergedHeaders;
}
return new Request(request.url, {
...options,
...secureOptions,
headers,
});
}
};

hooks = {
...options.hooks,
beforeRequest:
options.hooks && options.hooks.beforeRequest
? [securityWorker, ...options.hooks.beforeRequest]
: [securityWorker],
};
}

const request = this.ky(path.replace(/^\//, ""), {
...options,
headers,
searchParams: query,
body: body as any,
hooks,
});

<% if (config.unwrapResponseData) { %>
const responseFormat = format || this.format || undefined;
return (responseFormat === "json"
? request.json()
: responseFormat === "arrayBuffer"
? request.arrayBuffer()
: responseFormat === "blob"
? request.blob()
: responseFormat === "formData"
? request.formData()
: request.text()) as Promise<T>;
<% } else { %>
return request;
<% } %>
};
}
3 changes: 3 additions & 0 deletions templates/default/procedure-call.ejs
Expand Up @@ -72,6 +72,9 @@ const describeReturnType = () => {
case HTTP_CLIENT.AXIOS: {
return `Promise<AxiosResponse<${type}>>`
}
case HTTP_CLIENT.KY: {
return `KyResponse<${type}>`
}
default: {
return `Promise<HttpResponse<${type}, ${errorType}>`
}
Expand Down
3 changes: 3 additions & 0 deletions templates/modular/procedure-call.ejs
Expand Up @@ -72,6 +72,9 @@ const describeReturnType = () => {
case HTTP_CLIENT.AXIOS: {
return `Promise<AxiosResponse<${type}>>`
}
case HTTP_CLIENT.KY: {
return `KyResponse<${type}>`
}
default: {
return `Promise<HttpResponse<${type}, ${errorType}>`
}
Expand Down