Skip to content

feat: const object-style enum generation #1281

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
wants to merge 1 commit into
base: main
Choose a base branch
from
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
5 changes: 5 additions & 0 deletions .changeset/honest-feet-worry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"swagger-typescript-api": minor
---

Implement const object-style enum generation
7 changes: 7 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,12 @@ const generateCommand = defineCommand({
description: 'generate all "enum" types as union types (T1 | T2 | TN)',
default: codeGenBaseConfig.generateUnionEnums,
},
"generate-const-object-enums": {
type: "boolean",
description:
'generate all "enum" types as pairs of const objects and types derived from those objects\' keys. Mutually exclusive with, and pre-empted by, generateUnionEnums',
default: codeGenBaseConfig.generateConstObjectEnums, // TODO: collapse enum booleans into a single field taking an enum?
},
"http-client": {
type: "string",
description: `http client type (possible values: ${Object.values(
Expand Down Expand Up @@ -311,6 +317,7 @@ const generateCommand = defineCommand({
generateResponses: args.responses,
generateRouteTypes: args["route-types"],
generateUnionEnums: args["generate-union-enums"],
generateConstObjectEnums: args["generate-const-object-enums"],
httpClientType:
args["http-client"] || args.axios
? HTTP_CLIENT.AXIOS
Expand Down
3 changes: 3 additions & 0 deletions src/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const TsKeyword = {
Record: "Record",
Intersection: "&",
Union: "|",
Const: "const",
};

const TsCodeGenKeyword = {
Expand All @@ -54,6 +55,8 @@ export class CodeGenConfig {
/** CLI flag */
generateUnionEnums = false;
/** CLI flag */
generateConstObjectEnums = false;
/** CLI flag */
addReadonly = false;
enumNamesAsValues = false;
/** parsed swagger schema from getSwaggerObject() */
Expand Down
15 changes: 15 additions & 0 deletions src/schema-parser/schema-formatters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,21 @@ export class SchemaFormatters {
};
}

if (this.config.generateConstObjectEnums) {
const entries = parsedSchema.content
.map(({ key, value }) => {
return `${key}: ${value}`;
})
.join(",\n ");
return {
...parsedSchema,
$content: parsedSchema.content,
typeIdentifier: this.config.Ts.Keyword.Const,
content: `{\n ${entries}\n} as const;\nexport type ${parsedSchema.name} = (typeof ${parsedSchema.name})[keyof typeof ${parsedSchema.name}];`,
};
}

// Fallback: classic TypeScript enum
return {
...parsedSchema,
$content: parsedSchema.content,
Expand Down
3 changes: 3 additions & 0 deletions templates/base/data-contracts.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ const dataContractTemplates = {
type: (contract) => {
return `type ${contract.name}${buildGenerics(contract)} = ${contract.content}`;
},
'const': (contract) => {
return `const ${contract.name}${buildGenerics(contract)} = ${contract.content}`;
},
}
%>

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

exports[`basic > --generate-const-object-enums 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 ##
* ---------------------------------------------------------------
*/

/**
* FooBar
* @format int32
*/
export const IntEnumWithNames = {
Unknown: 0,
String: 1,
Int32: 2,
Int64: 3,
Double: 4,
DateTime: 5,
Test2: 6,
Test23: 7,
Tess44: 8,
BooFar: 9,
} as const;
export type IntEnumWithNames =
(typeof IntEnumWithNames)[keyof typeof IntEnumWithNames];

export const BooleanEnum = {
True: true,
False: false,
} as const;
export type BooleanEnum = (typeof BooleanEnum)[keyof typeof BooleanEnum];

export const NumberEnum = {
Value1: 1,
Value2: 2,
Value3: 3,
Value4: 4,
} as const;
export type NumberEnum = (typeof NumberEnum)[keyof typeof NumberEnum];

export const StringEnum = {
String1: "String1",
String2: "String2",
String3: "String3",
String4: "String4",
} as const;
export type StringEnum = (typeof StringEnum)[keyof typeof StringEnum];

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 = "http://localhost:8080/api/v1";
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) =>
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.clone() as HttpResponse<T, E>;
r.data = null as unknown as T;
r.error = null as unknown as E;

const data = !responseFormat
? r
: await response[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 No title
* @baseUrl http://localhost:8080/api/v1
*/
export class Api<
SecurityDataType extends unknown,
> extends HttpClient<SecurityDataType> {}
"
`;
Loading