Skip to content

Commit

Permalink
Release 7.0.0 (#208)
Browse files Browse the repository at this point in the history
* feat: add "onFormatRouteName" hook

* chore: try to add github workflows

* chore: rename gh workflow file to main

* chore: fix changelog after rebase

* fix incorrect working --route-types with --modular option   (#207)

* chore: try to fix modular route types problem

* fix: --route-types with --modular option; fix: better format namespace name (--route-types)

* feat: add extra output util functions

* chore: improve getTemplate function

* fix: getting template content by getTemplate by path

* fix: getTemplate by path

* chore: fix typings for rawModelTypes

* feat: add formatTSContent util function

* Fix boolean enum handling (#210)

* Add boolean enum example

* Fix boolean enum handling

* chore: up lodash to latest

* bump: up version to 7.0.0; feat: add returning `false` in `onCreateRoute` hook

Co-authored-by: Minjae Kim <[email protected]>
  • Loading branch information
js2me and haedaal authored Mar 19, 2021
1 parent 888249b commit 44c6f54
Show file tree
Hide file tree
Showing 27 changed files with 28,659 additions and 453 deletions.
8 changes: 8 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,14 @@
"cwd": "${workspaceFolder}",
"runtimeExecutable": "npm",
"runtimeArgs": ["run-script", "test:--templates"]
},
{
"name": "Debug test-all",
"type": "node",
"request": "launch",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "npm",
"runtimeArgs": ["run-script", "test-all"]
}
]
}
40 changes: 40 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,45 @@
# next release

# 7.0.0

BREAKING_CHANGES:
- format `namespace` name in `--route-types` as camelCase with upper first capitalized letter
`foo_bar` -> `FooBar`

Fixes:
- Incorrect working the `--route-types` option with `--modular` option (route types should be splitted on files)
- Fix critical bug linked with enums with boolean type (thanks @haedaal)

Features:
- Ability to return `false` in `onCreateRoute` hook, it allow to ignore route
- Add output util functions
```ts
createFile: (params: {
path: string;
fileName: string;
content: string;
withPrefix?: boolean;
}) => void;
renderTemplate: (
templateContent: string,
data: Record<string, unknown>,
etaOptions?: import("eta/dist/types/config").PartialConfig
) => string;
getTemplate: (params: {
fileName?: string;
name?: string;
path?: string;
}) => string
formatTSContent: (content: string) => string;


// ...

generateApi({ /* ... */ }).then(({ createFile, renderTemplate, getTemplate }) => {
// do something
})
```

# 6.4.2

Fixes:
Expand Down
23 changes: 22 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,21 +107,28 @@ interface GenerateApiParams {
}

export interface Hooks {
/** calls after parse schema component */
onCreateComponent: (component: SchemaComponent) => SchemaComponent | void;
/** calls after parse any kind of schema */
onParseSchema: (originalSchema: any, parsedSchema: any) => any | void;
onCreateRoute: (routeData: ParsedRoute) => ParsedRoute | void;
/** calls after parse route (return type: customized route (ParsedRoute), nothing change (void), false (ignore this route)) */
onCreateRoute: (routeData: ParsedRoute) => ParsedRoute | void | false;
/** Start point of work this tool (after fetching schema) */
onInit?: <C extends GenerateApiConfiguration["config"]>(configuration: C) => C | void;
/** customize configuration object before sending it to ETA templates */
onPrepareConfig?: <C extends GenerateApiConfiguration>(currentConfiguration: C) => C | void;
/** customize route name as you need */
onCreateRouteName?: (
routeNameInfo: RouteNameInfo,
rawRouteInfo: RawRouteInfo,
) => RouteNameInfo | void;
/** customize request params (path params, query params) */
onCreateRequestParams?: (
rawType: SchemaComponent["rawTypeData"],
) => SchemaComponent["rawTypeData"] | void;
/** customize name of model type */
onFormatTypeName?: (typeName: string, rawTypeName?: string) => string | void;
/** customize name of route (operationId), you can do it with using onCreateRouteName too */
onFormatRouteName?: (routeInfo: RawRouteInfo, templateRouteName: string) => string | void;
}

Expand Down Expand Up @@ -291,6 +298,7 @@ export interface GenerateApiConfiguration {
description: string;
content: string;
}[];
modelTypes: SchemaComponent[];
hasFormDataRoutes: boolean;
hasSecurityRoutes: boolean;
hasQueryRoutes: boolean;
Expand All @@ -308,6 +316,19 @@ export interface GenerateApiConfiguration {
export interface GenerateApiOutput {
configuration: GenerateApiConfiguration;
files: { name: string; content: string; declaration: { name: string; content: string } | null }[];
createFile: (params: {
path: string;
fileName: string;
content: string;
withPrefix?: boolean;
}) => void;
renderTemplate: (
templateContent: string,
data: Record<string, unknown>,
etaOptions?: import("eta/dist/types/config").PartialConfig,
) => string;
getTemplate: (params: { fileName?: string; name?: string; path?: string }) => string;
formatTSContent: (content: string) => string;
}

export declare function generateApi(
Expand Down
6 changes: 3 additions & 3 deletions package-lock.json

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

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "swagger-typescript-api",
"version": "6.4.2",
"version": "7.0.0",
"description": "Generate typescript/javascript api from swagger schema",
"scripts": {
"cli:json": "node index.js -r -d -p ./swagger-test-cli.json -n swagger-test-cli.ts",
Expand Down Expand Up @@ -55,7 +55,7 @@
"commander": "^6.2.1",
"eta": "^1.12.1",
"js-yaml": "^4.0.0",
"lodash": "^4.17.20",
"lodash": "^4.17.21",
"make-dir": "^3.1.0",
"nanoid": "^3.1.20",
"prettier": "^2.2.1",
Expand Down
8 changes: 7 additions & 1 deletion src/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,13 @@ const config = {
custom: "",
},
/** Record<templateName, templateContent> */
templatesToRender: {},
templatesToRender: {
api: "",
dataContracts: "",
httpClient: "",
routeTypes: "",
routeName: "",
},
toJS: false,
silent: false,
typePrefix: "",
Expand Down
8 changes: 6 additions & 2 deletions src/files.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,12 @@ const cleanDir = (path) => {

const pathIsExist = (path) => path && fs.existsSync(path);

const createFile = (pathTo, fileName, content) =>
fs.writeFileSync(resolve(__dirname, pathTo, `./${fileName}`), `${filePrefix}${content}`, _.noop);
const createFile = ({ path, fileName, content, withPrefix }) =>
fs.writeFileSync(
resolve(__dirname, path, `./${fileName}`),
`${withPrefix ? filePrefix : ""}${content}`,
_.noop,
);

module.exports = {
createFile,
Expand Down
34 changes: 29 additions & 5 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@ const { getSwaggerObject, fixSwaggerScheme, convertSwaggerObject } = require("./
const { createComponentsMap, filterComponentsMap } = require("./components");
const { createFile, pathIsExist, pathIsDir, createDir, cleanDir } = require("./files");
const { addToConfig, config } = require("./config");
const { getTemplates, getTemplatePaths } = require("./templates");
const { getTemplates, getTemplatePaths, renderTemplate, getTemplate } = require("./templates");
const constants = require("./constants");
const { generateOutputFiles } = require("./output");
const formatFileContent = require("./formatFileContent");

module.exports = {
constants: constants,
generateApi: ({
input,
output,
Expand Down Expand Up @@ -116,10 +118,13 @@ module.exports = {
const hasQueryRoutes = routes.some((route) => route.hasQuery);
const hasFormDataRoutes = routes.some((route) => route.hasFormDataParams);

const componentSchemas = filterComponentsMap(componentsMap, "schemas");

const rawConfiguration = {
apiConfig: createApiConfig(usageSchema, hasSecurityRoutes),
config,
modelTypes: _.map(filterComponentsMap(componentsMap, "schemas"), prepareModelType),
modelTypes: _.map(componentSchemas, prepareModelType),
rawModelTypes: componentSchemas,
hasFormDataRoutes,
hasSecurityRoutes,
hasQueryRoutes,
Expand Down Expand Up @@ -156,12 +161,27 @@ module.exports = {
if (!isDirPath) return file;

if (translateToJavaScript) {
createFile(output, file.name, file.content);
createFile(output, file.declaration.name, file.declaration.content);
createFile({
path: output,
fileName: file.name,
content: file.content,
withPrefix: true,
});
createFile({
path: output,
fileName: file.declaration.name,
content: file.declaration.content,
withPrefix: true,
});
if (!config.silent)
console.log(`✔️ your javascript api file created in "${output}"`);
} else {
createFile(output, file.name, file.content);
createFile({
path: output,
fileName: file.name,
content: file.content,
withPrefix: true,
});
if (!config.silent)
console.log(`✔️ your typescript api file created in "${output}"`);
}
Expand All @@ -172,6 +192,10 @@ module.exports = {
resolve({
files: generatedFiles,
configuration,
getTemplate,
renderTemplate,
createFile,
formatTSContent: formatFileContent,
});
})
.catch((e) => {
Expand Down
4 changes: 0 additions & 4 deletions src/modelTypes.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,6 @@ const prepareModelType = (typeInfo) => {
const typeData = getTypeData(typeInfo);
let { typeIdentifier, name: originalName, content, type, description } = typeData;

if (config.generateUnionEnums && typeIdentifier === "enum") {
typeIdentifier = "type";
}

const resultContent = formatters[type] ? formatters[type](content) : content;
const name = formatModelName(originalName);

Expand Down
74 changes: 49 additions & 25 deletions src/output.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,31 +47,61 @@ const createMultipleFileInfos = (templatesToRender, configuration) => {
const { fileNames, generateRouteTypes, generateClient } = configuration.config;
const modularApiFileInfos = [];

if (generateClient && routes.$outOfModule) {
const outOfModuleApiContent = renderTemplate(templatesToRender.api, {
...configuration,
route: configuration.routes.$outOfModule,
});

modularApiFileInfos.push(
createFileInfo(configuration, fileNames.outOfModuleApi, outOfModuleApiContent),
);
if (routes.$outOfModule) {
if (generateRouteTypes) {
const outOfModuleRouteContent = renderTemplate(templatesToRender.routeTypes, {
...configuration,
route: configuration.routes.$outOfModule,
});

modularApiFileInfos.push(
createFileInfo(configuration, fileNames.outOfModuleApi, outOfModuleRouteContent),
);
}
if (generateClient) {
const outOfModuleApiContent = renderTemplate(templatesToRender.api, {
...configuration,
route: configuration.routes.$outOfModule,
});

modularApiFileInfos.push(
createFileInfo(configuration, fileNames.outOfModuleApi, outOfModuleApiContent),
);
}
}

if (generateClient && routes.combined) {
if (routes.combined) {
modularApiFileInfos.push(
..._.reduce(
routes.combined,
(apiFileInfos, route) => {
const apiModuleContent = renderTemplate(templatesToRender.api, {
...configuration,
route,
});

return [
...apiFileInfos,
createFileInfo(configuration, classNameCase(route.moduleName), apiModuleContent),
];
if (generateRouteTypes) {
const routeModuleContent = renderTemplate(templatesToRender.routeTypes, {
...configuration,
route,
});

apiFileInfos.push(
createFileInfo(
configuration,
classNameCase(`${route.moduleName}_Route`),
routeModuleContent,
),
);
}

if (generateClient) {
const apiModuleContent = renderTemplate(templatesToRender.api, {
...configuration,
route,
});

apiFileInfos.push(
createFileInfo(configuration, classNameCase(route.moduleName), apiModuleContent),
);
}

return apiFileInfos;
},
[],
),
Expand All @@ -84,12 +114,6 @@ const createMultipleFileInfos = (templatesToRender, configuration) => {
fileNames.dataContracts,
renderTemplate(templatesToRender.dataContracts, configuration),
),
generateRouteTypes &&
createFileInfo(
configuration,
fileNames.routeTypes,
renderTemplate(templatesToRender.routeTypes, configuration),
),
generateClient &&
createFileInfo(
configuration,
Expand Down
2 changes: 2 additions & 0 deletions src/render/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const path = require("path");
const { classNameCase, formatDescription, internalCase } = require("../../common");
const { getComponentByRef } = require("../../components");
const { config } = require("../../config");
const { formatModelName } = require("../../modelNames");
const { getInlineParseContent, getParseContent, parseSchema } = require("../../schema");
const { formatters, inlineExtraFormatters } = require("../../typeFormatters");

Expand All @@ -16,6 +17,7 @@ module.exports = {
parseSchema,
formatters,
inlineExtraFormatters,
formatModelName,
fmtToJSDocLine: require("./fmtToJSDocLine"),
_: _,
require: (packageOrPath) => {
Expand Down
Loading

0 comments on commit 44c6f54

Please sign in to comment.