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 extra-templates modular approach #849

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
44 changes: 34 additions & 10 deletions src/code-gen-process.js
Original file line number Diff line number Diff line change
Expand Up @@ -324,17 +324,41 @@ class CodeGenProcess {

if (!_.isEmpty(configuration.extraTemplates)) {
for (const extraTemplate of configuration.extraTemplates) {
const content = this.templatesWorker.renderTemplate(
this.fileSystem.getFileContent(extraTemplate.path),
configuration,
);
output.push(
...(await this.createOutputFileInfo(
if(extraTemplate.modular){
for (const route of configuration.routes.combined) {
const extraTemplateContent = this.templatesWorker.renderTemplate(
this.fileSystem.getFileContent(extraTemplate.path),
{
...configuration,
route,
},
);

output.push(
...(await this.createOutputFileInfo(
configuration,
extraTemplate.name({
...configuration,
route,
}),
extraTemplateContent,
)),
);
}
}else{
const content = this.templatesWorker.renderTemplate(
this.fileSystem.getFileContent(extraTemplate.path),
configuration,
extraTemplate.name,
content,
)),
);
);
output.push(
...(await this.createOutputFileInfo(
configuration,
extraTemplate.name,
content,
)),
);
}

}
}

Expand Down
5 changes: 4 additions & 1 deletion src/util/file-system.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,10 @@ class FileSystem {
const __dirname = dirname(url.fileURLToPath(import.meta.url));
const absolutePath = resolve(__dirname, path, `./${fileName}`);
const fileContent = `${withPrefix ? FILE_PREFIX : ""}${content}`;

const dirPath = dirname(absolutePath);
if (!this.pathIsExist(dirPath)) {
this.createDir(dirPath);
}
return fs.writeFileSync(absolutePath, fileContent, _.noop);
};
}
Expand Down
51 changes: 51 additions & 0 deletions tests/spec/extra-templates/__snapshots__/basic.test.js.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

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

/**
Swagger Petstore
1.0.0
A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification
*/
export class Api {
private request(params: Record<string, any>) {
return fetch(params as any);
}
}
"
`;

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

/**
Swagger Petstore
1.0.0
A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification
*/
export class WrongPathParams1 {
private request(params: Record<string, any>) {
return fetch(params as any);
}
}
"
`;
65 changes: 65 additions & 0 deletions tests/spec/extra-templates/basic.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import * as fs from "node:fs/promises";
import * as os from "node:os";
import * as path from "node:path";

import { afterAll, beforeAll, describe, expect, test } from "vitest";

import { generateApi } from "../../../src/index.js";

describe("basic", async () => {
let tmpdir = "";

beforeAll(async () => {
tmpdir = await fs.mkdtemp(path.join(os.tmpdir(), "swagger-typescript-api"));
});

afterAll(async () => {
await fs.rm(tmpdir, { recursive: true });
});

test("--extra-templates", async () => {
await generateApi({
name: "schema",
input: path.resolve(import.meta.dirname, "schema.json"),
output: tmpdir,
silent: true,
extraTemplates: [
{
name: "external-template-name",
path: path.resolve(import.meta.dirname, "./templates/test.ejs")
},
],
});

const content = await fs.readFile(path.join(tmpdir, "external-template-name.ts"), {
encoding: "utf8",
});

expect(content).toMatchSnapshot();
});

test("--extra-templates-route", async () => {
await generateApi({
name: "schema",
input: path.resolve(import.meta.dirname, "schema.json"),
output: tmpdir,
silent: true,
extraTemplates: [
{
name: (config)=>{
console.log(config.route.moduleName)
return `contexts/${config.route.moduleName}Context`
},
path: path.resolve(import.meta.dirname, "./templates/test-route.ejs"),
modular: true
},
],
});

const content = await fs.readFile(path.join(tmpdir, "contexts/wrongPathParams1Context.ts"), {
encoding: "utf8",
});

expect(content).toMatchSnapshot();
});
});
36 changes: 36 additions & 0 deletions tests/spec/extra-templates/schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "Swagger Petstore",
"description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"name": "Swagger API Team"
},
"license": {
"name": "MIT"
}
},
"host": "petstore.swagger.io",
"basePath": "/api",
"schemes": ["http"],
"consumes": ["application/json"],
"produces": ["application/json"],
"paths": {
"/wrong-path-params1/{pathParam1}/{path_param2}/{path_param3}/:pathParam4": {
"delete": {
"description": "DDD",
"operationId": "wrong-path-params1",
"parameters": [],
"produces": ["application/json"],
"responses": {
"200": { "description": "Successfully deleted" }
},
"tags": ["key", "delete"]
}
}
},
"definitions": {
}
}
20 changes: 20 additions & 0 deletions tests/spec/extra-templates/templates/test-route.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<%
const { utils, route, config, modelTypes } = it;
const { _, pascalCase, require } = utils;
const apiClassName = pascalCase(route.moduleName);
%>

/**
<%= it.apiConfig.info.title %>

<%= it.apiConfig.info.version %>

<%= it.apiConfig.info.description %>

*/
export class <%= apiClassName %> {
private request(params: Record<string, any>) {
return fetch(params as any)
}
}

18 changes: 18 additions & 0 deletions tests/spec/extra-templates/templates/test.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<%
// console.info(it)
%>

/**
<%= it.apiConfig.info.title %>

<%= it.apiConfig.info.version %>

<%= it.apiConfig.info.description %>

*/
export class <%= it.config.apiClassName %> {
private request(params: Record<string, any>) {
return fetch(params as any)
}
}

Loading