Skip to content

Commit

Permalink
Release 6.4.0 (#197)
Browse files Browse the repository at this point in the history
* fix: bug with complex types; fix: bug with number enum with x-enumNames

* fix: problem with non existing title property in swagger.info; chore: add enums swagger schema

* chore: improve description in single api file

* feat: add "onFormatRouteName" hook

* chore: try to add github workflows

* docs: update README.md

* docs: update README

* bump: up version to 6.4.0

* chore: rename gh workflow file to main
  • Loading branch information
js2me authored Mar 5, 2021
1 parent 7d38f20 commit a975971
Show file tree
Hide file tree
Showing 60 changed files with 781 additions and 153 deletions.
27 changes: 27 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: CI

on:
pull_request:
branches:
- next

jobs:
test:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v1

- name: use node
uses: actions/setup-node@v1
with:
node-version: 10

- name: install deps
run: npm i

- name: simple-tests
run: npm run generate && npm run validate

- name: specific-tests
run: npm run test-specific
8 changes: 7 additions & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,10 @@ tests/**/*.d.js
swagger-test-cli
swagger-test-cli.*
templates
*.md
*.md
.github
node_modules
.openapi-generator
.vscode
assets
templates
4 changes: 2 additions & 2 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@
"request": "launch",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "npm",
"runtimeArgs": ["run-script", "cli:debug:json"]
"runtimeArgs": ["run-script", "cli:json"]
},
{
"name": "Debug YAML CLI",
"type": "node",
"request": "launch",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "npm",
"runtimeArgs": ["run-script", "cli:debug:yaml"]
"runtimeArgs": ["run-script", "cli:yaml"]
},
{
"name": "Debug Node",
Expand Down
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
# next release

# 6.4.0

Features:
- `onFormatRouteName(routeInfo: RawRouteInfo, templateRouteName: string)` hook. Allows to format route name, as you like :)

Fixes:
- Bug with wrong complex types (anyOf, oneOf, allOf) when some child schema contains only description
![example](./assets/changelog_assets/fixComplexTypeAny.jpg)
- Bug with number enums which have `x-enumNames`
- Problem with not existing `title` property in `info`

Minor:
- Improve description for complex types
- Improve description in single api file

# 6.3.0

Features:
Expand Down
72 changes: 38 additions & 34 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,49 +73,53 @@ Also you can use `npx`:
You can use this package from nodejs:
```js
const { generateApi } = require('swagger-typescript-api');
const path = require("path");
const fs = require("fs");

// example with url
/* NOTE: all fields are optional expect one of `output`, `url`, `spec` */
generateApi({
name: "MySuperbApi.ts", // name of output typescript file
url: 'http://api.com/swagger.json', // url where located swagger schema
})
.then(({ files, configuration }) => {
files.forEach(({ content, name }) => {
fs.writeFile(path, content);
});
})
.catch(e => console.error(e))

// example with local file
generateApi({
name: "ApiModule.ts", // name of output typescript file
input: resolve(process.cwd(), './foo/swagger.json') // path to swagger schema
})
.then(({ files, configuration }) => {
files.forEach(({ content, name }) => {
fs.writeFile(path, content);
});
})
.catch(e => console.error(e))

// example with parsed schema
generateApi({
name: "ApiModule.ts", // name of output typescript file
name: "MySuperbApi.ts",
output: path.resolve(process.cwd(), "./src/__generated__"),
url: 'http://api.com/swagger.json',
input: path.resolve(process.cwd(), './foo/swagger.json'),
spec: {
swagger: "2.0",
info: {
version: "1.0.0",
title: "Swagger Petstore",
},
host: "petstore.swagger.io",
basePath: "/api",
schemes: ["http"],
consumes: ["application/json"],
produces: ["application/json"],
paths: {
// ...
}
// ...
},
templates: path.resolve(process.cwd(), './api-templates'),
httpClientType: "axios", // or "fetch"
defaultResponseAsSuccess: false,
generateRouteTypes: false,
generateResponses: true,
toJS: false,
extractRequestParams: false,
prettier: {
printWidth: 120,
tabWidth: 2,
trailingComma: "all",
parser: "typescript",
},
defaultResponseType: "void",
singleHttpClient: true,
cleanOutput: false,
enumNamesAsValues: false,
moduleNameFirstTag: false,
generateUnionEnums: false,
extraTemplates: [],
hooks: {
onCreateComponent: (component) => {},
onCreateRequestParams: (rawType) => {},
onCreateRoute: (routeData) => {},
onCreateRouteName: (routeNameInfo, rawRouteInfo) => {},
onFormatRouteName: (routeInfo, templateRouteName) => {},
onFormatTypeName: (typeName, rawTypeName) => {},
onInit: (configuration) => {},
onParseSchema: (originalSchema, parsedSchema) => {},
onPrepareConfig: (currentConfiguration) => {},
}
})
.then(({ files, configuration }) => {
Expand Down
Binary file added assets/changelog_assets/fixComplexTypeAny.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
38 changes: 20 additions & 18 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ interface GenerateApiParams {
* extract request params to data contract (Also combine path params and query params into one object)
*/
extractRequestParams?: boolean;
prepareConfig?: <C extends GenerateApiConfiguration>(currentConfiguration: C) => C;
/**
* prettier configuration
*/
Expand All @@ -100,29 +99,32 @@ interface GenerateApiParams {
cleanOutput?: boolean;
enumNamesAsValues?: boolean;

hooks?: Partial<{
onCreateComponent: (component: SchemaComponent) => SchemaComponent | void;
onParseSchema: (originalSchema: any, parsedSchema: any) => any | void;
onCreateRoute: (routeData: ParsedRoute) => ParsedRoute | void;
/** 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;
onCreateRouteName?: (
routeNameInfo: RouteNameInfo,
rawRouteInfo: RawRouteInfo,
) => RouteNameInfo | void;
onCreateRequestParams?: (
rawType: SchemaComponent["rawTypeData"],
) => SchemaComponent["rawTypeData"] | void;
onFormatTypeName?: (typeName: string, rawTypeName?: string) => string | void;
}>;
hooks?: Partial<Hooks>;
/**
* extra templates
*/
extraTemplates?: { name: string; path: string }[];
}

export interface Hooks {
onCreateComponent: (component: SchemaComponent) => SchemaComponent | void;
onParseSchema: (originalSchema: any, parsedSchema: any) => any | void;
onCreateRoute: (routeData: ParsedRoute) => ParsedRoute | void;
/** 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;
onCreateRouteName?: (
routeNameInfo: RouteNameInfo,
rawRouteInfo: RawRouteInfo,
) => RouteNameInfo | void;
onCreateRequestParams?: (
rawType: SchemaComponent["rawTypeData"],
) => SchemaComponent["rawTypeData"] | void;
onFormatTypeName?: (typeName: string, rawTypeName?: string) => string | void;
onFormatRouteName?: (routeInfo: RawRouteInfo, templateRouteName: string) => string | void;
}

export interface RouteNameRouteInfo {}

export type RouteNameInfo = {
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

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

9 changes: 4 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
{
"name": "swagger-typescript-api",
"version": "6.3.0",
"description": "Create typescript api module from swagger schema",
"version": "6.4.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 --extract-request-params --enum-names-as-values",
"cli:json": "node index.js -r -d -p ./swagger-test-cli.json -n swagger-test-cli.ts",
"cli:yaml": "node index.js -r -d -p ./swagger-test-cli.yaml -n swagger-test-cli.ts",
"cli:debug:json": "node --nolazy index.js -r -d -p ./swagger-test-cli.json -n swagger-test-cli.ts --extract-request-params --enum-names-as-values",
"cli:debug:yaml": "node --nolazy index.js -p ./swagger-test-cli.yaml -n swagger-test-cli.ts",
"node": "node swagger-test-cli/generate.js",
"node:debug": "node --nolazy swagger-test-cli/generate.js",
"contributors": "all-contributors generate",
"cli:help": "node index.js -h",
"test-all": "node ./node_modules/npm-run-all/bin/npm-run-all/index.js generate validate test:* --continue-on-error",
"test-specific": "node ./node_modules/npm-run-all/bin/npm-run-all/index.js test:* --continue-on-error",
"generate": "node tests/generate.js",
"generate:debug": "node --nolazy tests/generate.js",
"validate": "node tests/validate.js",
Expand Down
12 changes: 11 additions & 1 deletion src/apiConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const { formatDescription } = require("./common");
const { TS_KEYWORDS } = require("./constants");

const createApiConfig = (swaggerSchema) => {
const { info, servers, host, basePath } = swaggerSchema;
const { info, servers, host, basePath, externalDocs, tags } = swaggerSchema;
const server = (servers && servers[0]) || { url: "" };
const { title = "No title", version, description: schemaDescription = "" } = info || {};
const { url: serverUrl } = server;
Expand All @@ -27,6 +27,14 @@ const createApiConfig = (swaggerSchema) => {
servers: servers || [],
basePath,
host,
externalDocs: _.merge(
{
url: "",
description: "",
},
externalDocs,
),
tags: _.compact(tags),
// TODO: unused, remove!
props: _.compact([
{
Expand All @@ -50,7 +58,9 @@ const createApiConfig = (swaggerSchema) => {
baseUrl: serverUrl,
title,
version,
// TODO: unused, remove
description,
// TODO: unused, remove
hasDescription: !!description.length,
};
};
Expand Down
1 change: 1 addition & 0 deletions src/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ const config = {
onCreateRequestParams: (rawType) => {},
onCreateRouteName: () => {},
onFormatTypeName: (typeName, rawTypeName) => {},
onFormatRouteName: (routeInfo, templateRouteName) => {},
},
defaultResponseType: TS_KEYWORDS.VOID,
singleHttpClient: false,
Expand Down
1 change: 1 addition & 0 deletions src/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const SCHEMA_TYPES = {
COMPLEX_ANY_OF: "anyOf",
COMPLEX_ALL_OF: "allOf",
COMPLEX_NOT: "not",
COMPLEX_UNKNOWN: "__unknown",
};

const HTTP_CLIENT = {
Expand Down
10 changes: 5 additions & 5 deletions src/routeNames.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ const getRouteName = (routeInfo) => {
const { routeNameDuplicatesMap, templatesToRender } = config;
const routeNameTemplate = templatesToRender.routeName;

if (!routeNameTemplate) {
throw new Error("🥵 route name template (route-name.eta) not found");
}

const routeName = renderTemplate(routeNameTemplate, {
const routeNameFromTemplate = renderTemplate(routeNameTemplate, {
routeInfo: routeInfo,
utils: require("./render/utils"),
config,
});

const routeName =
config.hooks.onFormatRouteName(routeInfo, routeNameFromTemplate) || routeNameFromTemplate;

const duplicateIdentifier = `${moduleName}|${routeName}`;

if (routeNameDuplicatesMap.has(duplicateIdentifier)) {
Expand Down
Loading

0 comments on commit a975971

Please sign in to comment.