Skip to content

Commit

Permalink
Merge branch 'master' of https://github.com/gaboe/rest2ts
Browse files Browse the repository at this point in the history
  • Loading branch information
gaboe committed Sep 2, 2024
2 parents 27b984e + 8e289c9 commit 3a61ab4
Show file tree
Hide file tree
Showing 42 changed files with 1,445 additions and 1,395 deletions.
16 changes: 14 additions & 2 deletions apps/cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ type ProgramProps = {
fileName: string | undefined;
cookies: boolean;
generateForAngular: boolean;
prefixesToRemove?: string[];
help: never;
};

Expand All @@ -29,13 +30,24 @@ program
)
.option("-f, --file-name <name>", "Output file name (defaults to Api.ts)")
.option("--cookies", "Generate API with cookies auth")
.option(
"-ptr, --prefixes-to-remove <prefixes>",
"Prefixes to remove from the generated code",
)
.helpOption("-h, --help", "Show help");

program.parse(process.argv);

const options = program.opts<ProgramProps>();

const { source, target, generateForAngular, fileName, cookies } = options;
const {
source,
target,
generateForAngular,
fileName,
cookies,
prefixesToRemove,
} = options;

if (!source) {
console.error("Error: Source -s is required.");
Expand All @@ -60,7 +72,7 @@ process.emitWarning = (warning, ...args) => {
originalEmitWarning.call(process, warning, ...(args as any));
};

generateApiContent(source, generateForAngular, cookies)
generateApiContent(source, generateForAngular, cookies, prefixesToRemove ?? [])
.then(content => {
if (content === null) {
console.error("Failed to generate api content");
Expand Down
7 changes: 5 additions & 2 deletions apps/cli/src/lib/generators/AngularServiceGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,8 +206,11 @@ const getContractResult = (
return Nothing;
};

export const generateAngularServices = (swagger: SwaggerSchema) => {
const endpoints = getEndpointsDescriptions(swagger).map(
export const generateAngularServices = (
swagger: SwaggerSchema,
prefixesToRemove: string[],
) => {
const endpoints = getEndpointsDescriptions(swagger, prefixesToRemove).map(
endpointDescription => {
const {
formattedParam: formattedRequestContractType,
Expand Down
16 changes: 14 additions & 2 deletions apps/cli/src/lib/generators/ApiDescriptionGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,19 @@ export type EndpointDescription = {
isFileResponse: boolean;
};

export const getEndpointsDescriptions = (swagger: SwaggerSchema) => {
const removePrefixes = (prop: string, prefixesToRemove: string[]): string => {
for (const prefix of prefixesToRemove) {
if (prop.startsWith(prefix)) {
return prop.substring(prefix.length);
}
}
return prop;
};

export const getEndpointsDescriptions = (
swagger: SwaggerSchema,
prefixesToRemove: string[],
) => {
const endpoints: EndpointDescription[][] = Object.keys(swagger.paths).map(
e => {
const pathObject = swagger.paths[e]!;
Expand All @@ -44,7 +56,7 @@ export const getEndpointsDescriptions = (swagger: SwaggerSchema) => {
const methods = [];
const generate = (methodType: MethodType, operation: Operation) => {
const formattedName = snakeToCamel(
`${methodType.toLowerCase()}_${prop}`,
`${methodType.toLowerCase()}_${removePrefixes(prop, prefixesToRemove)}`,
);
const name = `${formattedName.replace(version, "")}${
version === "V1" ? "" : version
Expand Down
7 changes: 5 additions & 2 deletions apps/cli/src/lib/generators/ServiceGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -486,8 +486,11 @@ const bodyBasedMethod = (
);
};

export const generateServices = (swagger: SwaggerSchema) => {
const endpoints = getEndpointsDescriptions(swagger);
export const generateServices = (
swagger: SwaggerSchema,
prefixesToRemove: string[],
) => {
const endpoints = getEndpointsDescriptions(swagger, prefixesToRemove);
const view = endpoints
.map(endpointDescription => {
const {
Expand Down
16 changes: 9 additions & 7 deletions apps/cli/src/lib/generators/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,15 @@ import { render } from "../renderers/Renderer";
const generateContent = (
schema: any,
isCookiesAuthEnabled: boolean = false,
prefixesToRemove: string[] = [],
) => {
const swaggerSchema = schema as SwaggerSchema;
const contracts = generateContracts(swaggerSchema);

const view = {
infrastructure: getInfrastructureTemplate(isCookiesAuthEnabled),
contracts,
services: generateServices(swaggerSchema),
services: generateServices(swaggerSchema, prefixesToRemove),
};
const content = render(
"{{{ infrastructure }}}\n{{{ contracts }}}\n{{{ services }}}",
Expand All @@ -28,14 +29,14 @@ const generateContent = (
return content;
};

const generateAngularContent = (schema: any) => {
const generateAngularContent = (schema: any, prefixesToRemove: string[]) => {
const swaggerSchema = schema as SwaggerSchema;
const contracts = generateContracts(swaggerSchema);

const view = {
contracts,
infrastructure: getAngularInfrastructureTemplate(),
services: generateAngularServices(swaggerSchema),
services: generateAngularServices(swaggerSchema, prefixesToRemove),
};
const content = render(
"{{{ infrastructure }}}\n{{{ contracts }}}\n\n{{{ services }}}\n",
Expand All @@ -48,6 +49,7 @@ export const generate = async (
api: any,
generateForAngular: boolean = false,
isCookiesAuthEnabled: boolean = false,
prefixesToRemove: string[] = [],
) => {
const logStep = () => console.log("⚡2/3 - Generating code");

Expand All @@ -63,12 +65,12 @@ export const generate = async (

logStep();
return generateForAngular
? generateAngularContent(response.data)
: generateContent(response.data, isCookiesAuthEnabled);
? generateAngularContent(response.data, prefixesToRemove)
: generateContent(response.data, isCookiesAuthEnabled, prefixesToRemove);
}

logStep();
return generateForAngular
? generateAngularContent(api)
: generateContent(api, isCookiesAuthEnabled);
? generateAngularContent(api, prefixesToRemove)
: generateContent(api, isCookiesAuthEnabled, prefixesToRemove);
};
8 changes: 7 additions & 1 deletion apps/cli/src/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export async function generateApiContent(
source: string,
generateForAngular: boolean,
cookies: boolean,
prefixesToRemove: string[],
): Promise<string | null> {
console.log(`🤖1/3 - Getting OpenAPI definition from ${source}`);

Expand All @@ -24,5 +25,10 @@ export async function generateApiContent(
return null;
}

return await generate(openAPI, generateForAngular == true, cookies == true);
return await generate(
openAPI,
generateForAngular == true,
cookies == true,
prefixesToRemove,
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -435,14 +435,14 @@ export type Cow = {
discriminator: string;
};

export type GetApiTestFetchResponse =
export type GetTestFetchResponse =
| FetchResponse<{status: string;
data?: Dog | Cat | Cow | null;}, 200>
| ErrorResponse;

export const getApiTestPath = () => `/api/test`;
export const getTestPath = () => `/api/test`;

export const getApiTest = (headers = new Headers()):
Promise<GetApiTestFetchResponse> => {
return apiGet(`${getApiUrl()}${getApiTestPath()}`, headers, {}) as Promise<GetApiTestFetchResponse>;
export const getTest = (headers = new Headers()):
Promise<GetTestFetchResponse> => {
return apiGet(`${getApiUrl()}${getTestPath()}`, headers, {}) as Promise<GetTestFetchResponse>;
}
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ export class ApiService {
this.baseUrl = baseUrl ?? "";
}

getApiTest(): Observable<ResponseResult<{status: string;
getTest(): Observable<ResponseResult<{status: string;
data?: Dog | Cat | Cow | null;}, 200>> {
return apiGet<ResponseResult<{status: string;
data?: Dog | Cat | Cow | null;}, 200>>(this.httpClient, `${this.baseUrl}/api/test`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -441,14 +441,14 @@ export type Cow = {
discriminator: string;
};

export type GetApiTestFetchResponse =
export type GetTestFetchResponse =
| FetchResponse<{status: string;
data?: Dog | Cat | Cow | null;}, 200>
| ErrorResponse;

export const getApiTestPath = () => `/api/test`;
export const getTestPath = () => `/api/test`;

export const getApiTest = (headers = new Headers()):
Promise<GetApiTestFetchResponse> => {
return apiGet(`${getApiUrl()}${getApiTestPath()}`, headers, {}) as Promise<GetApiTestFetchResponse>;
export const getTest = (headers = new Headers()):
Promise<GetTestFetchResponse> => {
return apiGet(`${getApiUrl()}${getTestPath()}`, headers, {}) as Promise<GetTestFetchResponse>;
}
10 changes: 5 additions & 5 deletions apps/cli/src/tests/__snapshots__/generate_anonymous_object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -421,14 +421,14 @@ export type ElectronicTradeBigRiskItemResponseDTO = {
validationNumber?: number | null;
};

export type GetApiTestFetchResponse =
export type GetTestFetchResponse =
| FetchResponse<{status: string;
data: ElectronicTradeBigRiskItemResponseDTO;}, 200>
| ErrorResponse;

export const getApiTestPath = () => `/api/test`;
export const getTestPath = () => `/api/test`;

export const getApiTest = (headers = new Headers()):
Promise<GetApiTestFetchResponse> => {
return apiGet(`${getApiUrl()}${getApiTestPath()}`, headers, {}) as Promise<GetApiTestFetchResponse>;
export const getTest = (headers = new Headers()):
Promise<GetTestFetchResponse> => {
return apiGet(`${getApiUrl()}${getTestPath()}`, headers, {}) as Promise<GetTestFetchResponse>;
}
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ export class ApiService {
this.baseUrl = baseUrl ?? "";
}

getApiTest(): Observable<ResponseResult<{status: string;
getTest(): Observable<ResponseResult<{status: string;
data: ElectronicTradeBigRiskItemResponseDTO;}, 200>> {
return apiGet<ResponseResult<{status: string;
data: ElectronicTradeBigRiskItemResponseDTO;}, 200>>(this.httpClient, `${this.baseUrl}/api/test`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -427,14 +427,14 @@ export type ElectronicTradeBigRiskItemResponseDTO = {
validationNumber?: number | null;
};

export type GetApiTestFetchResponse =
export type GetTestFetchResponse =
| FetchResponse<{status: string;
data: ElectronicTradeBigRiskItemResponseDTO;}, 200>
| ErrorResponse;

export const getApiTestPath = () => `/api/test`;
export const getTestPath = () => `/api/test`;

export const getApiTest = (headers = new Headers()):
Promise<GetApiTestFetchResponse> => {
return apiGet(`${getApiUrl()}${getApiTestPath()}`, headers, {}) as Promise<GetApiTestFetchResponse>;
export const getTest = (headers = new Headers()):
Promise<GetTestFetchResponse> => {
return apiGet(`${getApiUrl()}${getTestPath()}`, headers, {}) as Promise<GetTestFetchResponse>;
}
10 changes: 5 additions & 5 deletions apps/cli/src/tests/__snapshots__/generate_auth_login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -449,16 +449,16 @@ export type ProblemDetails = {
instance?: string | null;
};

export type PostApiAuthLoginFetchResponse =
export type PostAuthLoginFetchResponse =
| FetchResponse<AuthResult, 200>
| FetchResponse<ProblemDetails, 400>
| ErrorResponse;

export const postApiAuthLoginPath = () => `/api/Auth/login`;
export const postAuthLoginPath = () => `/api/Auth/login`;

export const postApiAuthLogin = (requestContract: AuthRequest, headers = new Headers()):
Promise<PostApiAuthLoginFetchResponse> => {
export const postAuthLogin = (requestContract: AuthRequest, headers = new Headers()):
Promise<PostAuthLoginFetchResponse> => {
const requestData = getApiRequestData<AuthRequest>(requestContract, false);

return apiPost(`${getApiUrl()}${postApiAuthLoginPath()}`, requestData, headers) as Promise<PostApiAuthLoginFetchResponse>;
return apiPost(`${getApiUrl()}${postAuthLoginPath()}`, requestData, headers) as Promise<PostAuthLoginFetchResponse>;
}
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ export class ApiService {
this.baseUrl = baseUrl ?? "";
}

postApiAuthLogin(requestContract: AuthRequest): Observable<ResponseResult<AuthResult, 200> | ResponseResult<ProblemDetails, 400>> {
postAuthLogin(requestContract: AuthRequest): Observable<ResponseResult<AuthResult, 200> | ResponseResult<ProblemDetails, 400>> {
const requestData = getApiRequestData<AuthRequest>(requestContract, false);

return apiPost<ResponseResult<AuthResult, 200> | ResponseResult<ProblemDetails, 400>>(this.httpClient, `${this.baseUrl}/api/Auth/login`, requestData);
Expand Down
10 changes: 5 additions & 5 deletions apps/cli/src/tests/__snapshots__/generate_auth_login_cookies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -455,16 +455,16 @@ export type ProblemDetails = {
instance?: string | null;
};

export type PostApiAuthLoginFetchResponse =
export type PostAuthLoginFetchResponse =
| FetchResponse<AuthResult, 200>
| FetchResponse<ProblemDetails, 400>
| ErrorResponse;

export const postApiAuthLoginPath = () => `/api/Auth/login`;
export const postAuthLoginPath = () => `/api/Auth/login`;

export const postApiAuthLogin = (requestContract: AuthRequest, headers = new Headers()):
Promise<PostApiAuthLoginFetchResponse> => {
export const postAuthLogin = (requestContract: AuthRequest, headers = new Headers()):
Promise<PostAuthLoginFetchResponse> => {
const requestData = getApiRequestData<AuthRequest>(requestContract, false);

return apiPost(`${getApiUrl()}${postApiAuthLoginPath()}`, requestData, headers) as Promise<PostApiAuthLoginFetchResponse>;
return apiPost(`${getApiUrl()}${postAuthLoginPath()}`, requestData, headers) as Promise<PostAuthLoginFetchResponse>;
}
10 changes: 5 additions & 5 deletions apps/cli/src/tests/__snapshots__/generate_bracket_params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -440,22 +440,22 @@ export type ProductItemDTO = {
hidden?: boolean | null;
};

export type GetApiProducersFetchResponse =
export type GetProducersFetchResponse =
| FetchResponse<ProducerItemDTO[], 200>
| FetchResponse<ExceptionDTO, 401>
| FetchResponse<ExceptionDTO, 403>
| FetchResponse<ExceptionDTO, 500>
| ErrorResponse;

export const getApiProducersPath = () => `/api/producers`;
export const getProducersPath = () => `/api/producers`;

export const getApiProducers = (filterTerm?: string, filterHidden?: number, filterRegion?: string, filterCategory?: string, headers = new Headers()):
Promise<GetApiProducersFetchResponse> => {
export const getProducers = (filterTerm?: string, filterHidden?: number, filterRegion?: string, filterCategory?: string, headers = new Headers()):
Promise<GetProducersFetchResponse> => {
const queryParams = {
"filter[term]": filterTerm,
"filter[hidden]": filterHidden,
"filter[region]": filterRegion,
"filter[category]": filterCategory
}
return apiGet(`${getApiUrl()}${getApiProducersPath()}`, headers, queryParams) as Promise<GetApiProducersFetchResponse>;
return apiGet(`${getApiUrl()}${getProducersPath()}`, headers, queryParams) as Promise<GetProducersFetchResponse>;
}
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ export class ApiService {
this.baseUrl = baseUrl ?? "";
}

getApiProducers(filterTerm?: string, filterHidden?: number, filterRegion?: string, filterCategory?: string): Observable<ResponseResult<ProducerItemDTO[], 200> | ResponseResult<ExceptionDTO, 401> | ResponseResult<ExceptionDTO, 403> | ResponseResult<ExceptionDTO, 500>> {
getProducers(filterTerm?: string, filterHidden?: number, filterRegion?: string, filterCategory?: string): Observable<ResponseResult<ProducerItemDTO[], 200> | ResponseResult<ExceptionDTO, 401> | ResponseResult<ExceptionDTO, 403> | ResponseResult<ExceptionDTO, 500>> {
const queryParams = {
"filter[term]": filterTerm,
"filter[hidden]": filterHidden,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -446,22 +446,22 @@ export type ProductItemDTO = {
hidden?: boolean | null;
};

export type GetApiProducersFetchResponse =
export type GetProducersFetchResponse =
| FetchResponse<ProducerItemDTO[], 200>
| FetchResponse<ExceptionDTO, 401>
| FetchResponse<ExceptionDTO, 403>
| FetchResponse<ExceptionDTO, 500>
| ErrorResponse;

export const getApiProducersPath = () => `/api/producers`;
export const getProducersPath = () => `/api/producers`;

export const getApiProducers = (filterTerm?: string, filterHidden?: number, filterRegion?: string, filterCategory?: string, headers = new Headers()):
Promise<GetApiProducersFetchResponse> => {
export const getProducers = (filterTerm?: string, filterHidden?: number, filterRegion?: string, filterCategory?: string, headers = new Headers()):
Promise<GetProducersFetchResponse> => {
const queryParams = {
"filter[term]": filterTerm,
"filter[hidden]": filterHidden,
"filter[region]": filterRegion,
"filter[category]": filterCategory
}
return apiGet(`${getApiUrl()}${getApiProducersPath()}`, headers, queryParams) as Promise<GetApiProducersFetchResponse>;
return apiGet(`${getApiUrl()}${getProducersPath()}`, headers, queryParams) as Promise<GetProducersFetchResponse>;
}
Loading

0 comments on commit 3a61ab4

Please sign in to comment.