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
6 changes: 6 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,11 @@ const generateCommand = defineCommand({
description: "sort routes in alphabetical order",
default: codeGenBaseConfig.sortRoutes,
},
"sort-route-params": {
type: "boolean",
description: "sort route params from path order",
default: codeGenBaseConfig.sortRouteParams,
},
"sort-types": {
type: "boolean",
description: "sort fields and types",
Expand Down Expand Up @@ -324,6 +329,7 @@ const generateCommand = defineCommand({
silent: args.silent,
singleHttpClient: args["single-http-client"],
sortRoutes: args["sort-routes"],
sortRouteParams: args["sort-route-params"],
sortTypes: args["sort-types"],
templates: args.templates,
toJS: args.js,
Expand Down
1 change: 1 addition & 0 deletions src/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ export class CodeGenConfig {
disableThrowOnError = false;
sortTypes = false;
sortRoutes = false;
sortRouteParams = false;
templatePaths = {
/** `templates/base` */
base: "",
Expand Down
26 changes: 21 additions & 5 deletions templates/default/procedure-call.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,27 @@ const rawWrapperArgs = config.extractRequestParams ?
requestConfigParam,
])

const wrapperArgs = _
// Sort by optionality
.sortBy(rawWrapperArgs, [o => o.optional])
.map(argToTmpl)
.join(', ')

const requiredArgs = rawWrapperArgs.filter((o) => !o.optional)
const optionalArgs = rawWrapperArgs.filter((o) => o.optional)

// sort by params index of params in path
if (config.sortRouteParams) {
requiredArgs.sort(({name}) => {
const idx = path.indexOf(`{${name}}`)
if (idx === -1) {
return Infinity
}
return idx
})
}

const sortedRawWrapperArgs = [
...requiredArgs,
...optionalArgs
]

const wrapperArgs = sortedRawWrapperArgs.map(argToTmpl).join(', ')

// RequestParams["type"]
const requestContentKind = {
Expand Down
1 change: 1 addition & 0 deletions tests/extended.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ describe("extended", async () => {
generateClient: true,
generateRouteTypes: true,
sortRoutes: true,
sortRouteParams: true,
sortTypes: true,
});

Expand Down
316 changes: 316 additions & 0 deletions tests/spec/sortRouteParams/__snapshots__/basic.test.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,316 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`basic > --sort-route-params 1`] = `
"/* eslint-disable */
/* tslint:disable */
// @ts-nocheck
/*
* ---------------------------------------------------------------
* ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
* ## ##
* ## AUTHOR: acacode ##
* ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
* ---------------------------------------------------------------
*/

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;

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 = "https://6-dot-authentiqio.appspot.com";
private securityData: SecurityDataType | null = null;
private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"];
private abortControllers = new Map<CancelToken, AbortController>();
private customFetch = (...fetchParams: Parameters<typeof fetch>) =>
fetch(...fetchParams);

private baseApiParams: RequestParams = {
credentials: "same-origin",
headers: {},
redirect: "follow",
referrerPolicy: "no-referrer",
};

constructor(apiConfig: ApiConfig<SecurityDataType> = {}) {
Object.assign(this, apiConfig);
}

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> = {
[ContentType.Json]: (input: any) =>
input !== null && (typeof input === "object" || typeof input === "string")
? JSON.stringify(input)
: input,
[ContentType.JsonApi]: (input: any) =>
input !== null && (typeof input === "object" || typeof input === "string")
? JSON.stringify(input)
: input,
[ContentType.Text]: (input: any) =>
input !== null && typeof input !== "string"
? JSON.stringify(input)
: input,
[ContentType.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());
},
[ContentType.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
}: 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 || ContentType.Json];
const responseFormat = format || requestParams.format;

return this.customFetch(
\`\${baseUrl || this.baseUrl || ""}\${path}\${queryString ? \`?\${queryString}\` : ""}\`,
{
...requestParams,
headers: {
...(requestParams.headers || {}),
...(type && type !== ContentType.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 (cancelToken) {
this.abortControllers.delete(cancelToken);
}

if (!response.ok) throw data;
return data;
});
};
}

/**
* @title Authentiq
* @version 6
* @license Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html)
* @termsOfService http://authentiq.com/terms/
* @baseUrl https://6-dot-authentiqio.appspot.com
* @contact Authentiq team <hello@authentiq.com> (http://authentiq.io/support)
*
* Strong authentication, without the passwords.
*/
export class Api<
SecurityDataType extends unknown,
> extends HttpClient<SecurityDataType> {
key = {
/**
* @description Register a new ID \`JWT(sub, devtoken)\` v5: \`JWT(sub, pk, devtoken, ...)\` See: https://github.com/skion/authentiq/wiki/JWT-Examples
*
* @tags key, post
* @name KeyRegister
* @request POST:/key/{PK}/{JobID}/
*/
keyRegister: (
pk: string,
jobId: string,
body: any,
params: RequestParams = {},
) =>
this.request<
{
/** revoke key */
secret?: string;
/** registered */
status?: string;
},
any
>({
path: \`/key/\${pk}/\${jobId}/\`,
method: "POST",
body: body,
format: "json",
...params,
}),
};
}
"
`;
Loading