Skip to content

Commit 131225d

Browse files
authored
release 1.4.0 (#20)
* test(internal): speed improve validate generated ts api modules * BREAKING_CHANGE: default typescript api file name (api.ts -> Api.ts) * feat: improve response body type definitions * chore(docs): add gtihub funding * [Bugfix] Response type does not de-reference $refs (#19) * chore: add common test schemas * refactor: encapsulate nodejs.fs module usage; feat: dereference components responses + improve types * chore: add specific comments for calling src/index.js on unix like machines via nodejs * chore: update gitignore (add hidden test cli file) * fix: JSDOC comments * [Features] - response declarations, "default" status codes as success response types (#17) * feat: add @returns keywords into each request comments description (request responses) * feat: prettify descriptions * feat: add response declarations in request description; feat: typed bad responses * feat: -d, --default-as-success option (ability to use "default" success response status code) * chore: add common test schemas * fix: description of defaultResponseAsSuccess option * chore: rename setConfig to addToConfig * chore: add specific comments for calling src/index.js on unix like machines via nodejs * feat: move responses declarations into flag '-r, --responses'; chore(test): add manual test for new option; docs: update CHANGELOG + README * fix: format description (end \n character) * bump: up version to 1.4.0
1 parent 36524ef commit 131225d

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

73 files changed

+10136
-8360
lines changed

.github/FUNDING.yml

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
open_collective: acacode
2+
ko_fi: acacode

.gitignore

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
node_modules
22
.vscode
3-
swagger-test-cli.ts
3+
swagger-test-cli.*

.vscode/launch.json

+10-1
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,22 @@
55
"version": "0.2.0",
66
"configurations": [
77
{
8-
"name": "Launch via npm",
8+
"name": "Debug generate",
99
"type": "node",
1010
"request": "launch",
1111
"cwd": "${workspaceFolder}",
1212
"runtimeExecutable": "npm",
1313
"runtimeArgs": ["run-script", "generate:debug"],
1414
"port": 9229
15+
},
16+
{
17+
"name": "Debug CLI",
18+
"type": "node",
19+
"request": "launch",
20+
"cwd": "${workspaceFolder}",
21+
"runtimeExecutable": "npm",
22+
"runtimeArgs": ["run-script", "cli:debug"],
23+
"port": 9229
1524
}
1625
]
1726
}

CHANGELOG.md

+16
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,19 @@
1+
# 1.4.0
2+
Breaking Changes:
3+
- Rename default typescript output api file name (prev `api.ts`, now `Api.ts`)
4+
Features:
5+
- `-d, --default-as-success` option. Allows to use "default" status codes as success response type
6+
- `-r, --responses` option. Response declarations in request rescription
7+
This option adds comments of the possible responses from request
8+
![responses comments](./assets/changelog_assets/responses-comments.jpg)
9+
Also typings for `.catch()` callback
10+
![responses catch types](./assets/changelog_assets/responses-catch-types.jpg)
11+
- Improve response body type definitions
12+
- Types for bad responses
13+
Changes:
14+
- \[minor\] fix jsdoc comments space
15+
![right comments space](./assets/changelog_assets/right-comments-space.jpg)
16+
117
# 1.3.0
218
Features:
319
- Api module description from schema info

README.md

+13-8
Original file line numberDiff line numberDiff line change
@@ -25,18 +25,23 @@ All examples you can find [**here**](https://github.com/acacode/swagger-typescri
2525

2626
## 📄 Usage
2727

28-
```cool
28+
```muse
2929
Usage: sta [options]
3030
Usage: swagger-typescript-api [options]
3131
3232
Options:
33-
-v, --version output the current version
34-
-p, --path <path> path/url to swagger scheme
35-
-o, --output <output> output path of typescript api file (default: "./")
36-
-n, --name <name> name of output typescript api file (default: "api.ts")
37-
--route-types generate type definitions for API routes (default: false)
38-
--no-client do not generate an API class
39-
-h, --help output usage information
33+
-v, --version output the current version
34+
-p, --path <path> path/url to swagger scheme
35+
-o, --output <output> output path of typescript api file (default: "./")
36+
-n, --name <name> name of output typescript api file (default: "Api.ts")
37+
-d, --default-as-success use "default" response status code as success response too.
38+
some swagger schemas use "default" response status code
39+
as success response type by default. (default: false)
40+
-r, --responses generate additional information about request responses
41+
also add typings for bad responses
42+
--route-types generate type definitions for API routes (default: false)
43+
--no-client do not generate an API class
44+
-h, --help output usage information
4045
```
4146

4247
Also you can use `npx`:
Loading
Loading
40.2 KB
Loading

index.d.ts

+28-12
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,15 @@
11

2-
interface BaseGenerateApiParams {
2+
interface GenerateApiParams {
3+
4+
/**
5+
* path to swagger schema
6+
*/
7+
input: string;
8+
9+
/**
10+
* url to swagger schema
11+
*/
12+
url: string;
313

414
/**
515
* default 'api.ts'
@@ -10,23 +20,29 @@ interface BaseGenerateApiParams {
1020
* path to folder where will been located the created api module
1121
*/
1222
output?: string;
13-
}
14-
15-
interface LocalFileGenerateApiParams extends BaseGenerateApiParams {
23+
24+
/**
25+
* generate type definitions for API routes (default: false)
26+
*/
27+
generateRouteTypes?: boolean;
1628

1729
/**
18-
* path to swagger schema
30+
* do not generate an API class
1931
*/
20-
input: string;
21-
}
32+
generateClient?: boolean;
2233

23-
interface UrlGenerateApiParams extends BaseGenerateApiParams {
34+
/**
35+
* use "default" response status code as success response too.
36+
* some swagger schemas use "default" response status code as success response type by default.
37+
*/
38+
defaultResponseAsSuccess?: boolean;
2439

2540
/**
26-
* url to swagger schema
41+
* generate additional information about request responses
42+
* also add typings for bad responses
2743
*/
28-
url: string;
44+
generateResponses?: boolean;
2945
}
3046

31-
export declare function generateApi(params: LocalFileGenerateApiParams): Promise<string>
32-
export declare function generateApi(params: UrlGenerateApiParams): Promise<string>
47+
export declare function generateApi(params: Omit<GenerateApiParams, "url">): Promise<string>
48+
export declare function generateApi(params: Omit<GenerateApiParams, "input">): Promise<string>

index.js

+24-2
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,41 @@ program
1616
.description("Generate api via swagger scheme.\nSupports OA 3.0, 2.0, JSON, yaml.")
1717
.requiredOption('-p, --path <path>', 'path/url to swagger scheme')
1818
.option('-o, --output <output>', 'output path of typescript api file', './')
19-
.option('-n, --name <name>', 'name of output typescript api file', 'api.ts')
19+
.option('-n, --name <name>', 'name of output typescript api file', 'Api.ts')
20+
.option(
21+
'-d, --default-as-success',
22+
'use "default" response status code as success response too.\n' +
23+
'some swagger schemas use "default" response status code as success response type by default.',
24+
false
25+
)
26+
.option(
27+
'-r, --responses',
28+
'generate additional information about request responses\n' +
29+
'also add typings for bad responses',
30+
false,
31+
)
2032
.option('--route-types', 'generate type definitions for API routes', false)
2133
.option('--no-client', 'do not generate an API class', false);
2234

2335
program.parse(process.argv);
2436

25-
const { path, output, name, routeTypes, client } = program;
37+
const {
38+
path,
39+
output,
40+
name,
41+
routeTypes,
42+
client,
43+
defaultAsSuccess,
44+
responses,
45+
} = program;
2646

2747
generateApi({
2848
name,
2949
url: path,
3050
generateRouteTypes: routeTypes,
3151
generateClient: client,
52+
defaultResponseAsSuccess: defaultAsSuccess,
53+
generateResponses: responses,
3254
input: resolve(process.cwd(), path),
3355
output: resolve(process.cwd(), output || '.')
3456
})

package-lock.json

+1-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+7-4
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,20 @@
11
{
22
"name": "swagger-typescript-api",
3-
"version": "1.3.0",
3+
"version": "1.4.0",
44
"description": "Create typescript api module from swagger schema",
55
"scripts": {
6-
"cli": "node index.js -p ./tests/schemas/v3.0/personal-api-example.json -n swagger-test-cli.ts",
6+
"cli": "node index.js -d -p ./swagger-test-cli.json -n swagger-test-cli.ts",
7+
"cli:debug": "node --nolazy --inspect-brk=9229 index.js -p ./tests/schemas/v2.0/adafruit.yaml -n swagger-test-cli.ts",
78
"cli:help": "node index.js -h",
8-
"test:all": "npm-run-all generate validate test:routeTypes test:noClient --continue-on-error",
9+
"test:all": "npm-run-all generate validate test:routeTypes test:noClient test:defaultAsSuccess test:responses --continue-on-error",
910
"generate": "node tests/generate.js",
1011
"generate:debug": "node --nolazy --inspect-brk=9229 tests/generate.js",
1112
"validate": "node tests/validate.js",
1213
"validate:debug": "node --nolazy --inspect-brk=9229 tests/validate.js",
1314
"test:routeTypes": "node tests/spec/routeTypes/test.js",
14-
"test:noClient": "node tests/spec/noClient/test.js"
15+
"test:noClient": "node tests/spec/noClient/test.js",
16+
"test:defaultAsSuccess": "node tests/spec/defaultAsSuccess/test.js",
17+
"test:responses": "node tests/spec/responses/test.js"
1518
},
1619
"author": "acacode",
1720
"license": "MIT",

src/apiConfig.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
const _ = require("lodash")
1+
const { formatDescription } = require("./common");
22

33
const createApiConfig = ({ info, servers, }) => {
44
const server = (servers && servers[0]) || { url: '' }
@@ -29,7 +29,7 @@ const createApiConfig = ({ info, servers, }) => {
2929
baseUrl: server.url,
3030
title: info.title,
3131
version: info.version,
32-
description: _.replace(info.description, /\*\//g, "*\/"),
32+
description: formatDescription(info.description),
3333
}
3434
}
3535

src/common.js

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
const _ = require("lodash");
2+
3+
module.exports = {
4+
formatDescription: (description, inline) => {
5+
let prettified = description;
6+
7+
prettified = _.replace(prettified, /\*\//g, "*\/");
8+
9+
const hasMultipleLines = _.includes(prettified, '\n');
10+
11+
if (!hasMultipleLines)
12+
return prettified;
13+
14+
if (inline) {
15+
return _(prettified)
16+
.split(/\n/g)
17+
.map(part => _.trim(part))
18+
.compact()
19+
.join(' ')
20+
.valueOf()
21+
}
22+
23+
return _.replace(prettified, /\n$/g, '')
24+
}
25+
}

src/components.js

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
const _ = require("lodash");
2+
const { parseSchema } = require("./schema");
3+
const { addToConfig } = require("./config");
4+
5+
/**
6+
*
7+
* @typedef TypeInfo
8+
* {
9+
* typeName: "Foo",
10+
* componentName: "schemas",
11+
* rawTypeData: {...},
12+
* typeData: {...} (result parseSchema())
13+
* }
14+
*/
15+
16+
/**
17+
* @returns {{ "#/components/schemas/Foo": TypeInfo, ... }}
18+
*/
19+
const createComponentsMap = components => {
20+
const componentsMap = _.reduce(components, (map, component, componentName) => {
21+
_.each(component, (rawTypeData, typeName) => {
22+
// only map data for now
23+
map[`#/components/${componentName}/${typeName}`] = {
24+
typeName,
25+
rawTypeData,
26+
componentName,
27+
typeData: null,
28+
}
29+
})
30+
return map;
31+
}, {})
32+
33+
addToConfig({ componentsMap })
34+
35+
return componentsMap;
36+
}
37+
38+
39+
40+
/**
41+
* @returns {TypeInfo[]}
42+
*/
43+
const filterComponentsMap = (componentsMap, componentName) =>
44+
_.filter(componentsMap, (v, ref) => _.startsWith(ref, `#/components/${componentName}`))
45+
46+
47+
/** @returns {{ type, typeIdentifier, name, description, content }} */
48+
const getTypeData = typeInfo => {
49+
if (!typeInfo.typeData) {
50+
typeInfo.typeData = parseSchema(typeInfo.rawTypeData, typeInfo.typeName)
51+
}
52+
53+
return typeInfo.typeData;
54+
}
55+
56+
module.exports = {
57+
getTypeData,
58+
createComponentsMap,
59+
filterComponentsMap,
60+
}

src/config.js

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
2+
const config = {
3+
/** CLI flag */
4+
generateResponses: false,
5+
/** CLI flag */
6+
defaultResponseAsSuccess: false,
7+
/** CLI flag */
8+
generateRouteTypes: false,
9+
/** CLI flag */
10+
generateClient: true,
11+
/** parsed swagger schema from getSwaggerObject() */
12+
swaggerSchema: null,
13+
/** { "#/components/schemas/Foo": @TypeInfo, ... } */
14+
componentsMap: {},
15+
}
16+
17+
/** needs to use data everywhere in project */
18+
module.exports = {
19+
addToConfig: configParts => Object.assign(config, configParts),
20+
config,
21+
}

src/constants.js

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
module.exports = {
2+
DEFAULT_PRIMITIVE_TYPE: "any",
3+
DEFAULT_BODY_ARG_NAME: "data",
4+
DEFAULT_CONTENT_TYPE: "application/json",
5+
SUCCESS_RESPONSE_STATUS_RANGE: [200, 300],
6+
}

src/files.js

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
const _ = require("lodash");
2+
const fs = require("fs");
3+
const { resolve } = require("path");
4+
5+
const getFileContent = path =>
6+
fs.readFileSync(path, { encoding: 'UTF-8' })
7+
8+
const pathIsExist = path =>
9+
path && fs.existsSync(path)
10+
11+
const createFile = (pathTo, fileName, content) =>
12+
fs.writeFileSync(resolve(__dirname, pathTo, `./${fileName}`), content, _.noop)
13+
14+
const getTemplate = templateName =>
15+
getFileContent(resolve(__dirname, `./templates/${templateName}.mustache`))
16+
17+
module.exports = {
18+
getTemplate,
19+
createFile,
20+
pathIsExist,
21+
getFileContent,
22+
}

0 commit comments

Comments
 (0)