Skip to content

Commit

Permalink
Release 1.12.0 (#77)
Browse files Browse the repository at this point in the history
* fix: handling x-omitempty property for definition properties (#68)

* Complete #69 add spec option to convert schema object (#70)

* chore: rename exception message for specProperty test

* fix: enums with spaces throw an error

* chore: remove "const enum" from client.mustache

* fix: problem of additional properties #76

* fix: problem of anyOf complex type (intersection of primitive ts types)

* fix: problem of pattern fields treating as operations #75

* docs: update CHANGELOG

* bump: update project version to 1.12.0

* fix: problem of typings "spec" property for generateApi function

Co-authored-by: Jennie <jennie.ji@hotmail.com>
  • Loading branch information
js2me and JennieJi authored Aug 19, 2020
1 parent 7a23584 commit a163999
Show file tree
Hide file tree
Showing 62 changed files with 2,564 additions and 1,783 deletions.
9 changes: 3 additions & 6 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,23 @@
"request": "launch",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "npm",
"runtimeArgs": ["run-script", "generate:debug"],
"port": 9229
"runtimeArgs": ["run-script", "generate:debug"]
},
{
"name": "Debug JSON CLI",
"type": "node",
"request": "launch",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "npm",
"runtimeArgs": ["run-script", "cli:debug:json"],
"port": 9229
"runtimeArgs": ["run-script", "cli:debug:json"]
},
{
"name": "Debug YAML CLI",
"type": "node",
"request": "launch",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "npm",
"runtimeArgs": ["run-script", "cli:debug:yaml"],
"port": 9229
"runtimeArgs": ["run-script", "cli:debug:yaml"]
}
]
}
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
# next release


# 1.12.0

Features:
- Can provide ability to generate from swagger JSON directly not from a file? #69 (Thanks @JennieJi)

Fixes:
- handling `x-omitempty` property for definition properties #68
- Additional properties map to empty interfaces (OpenAPI v3) #76
- Pattern fields in Path Item Object are treated as operations #75
- Remove const enum from default template #73
- enums with spaces throw an error #71


# 1.11.0

Features:
Expand Down
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,29 @@ generateApi({
.then(sourceFile => fs.writeFile(path, sourceFile))
.catch(e => console.error(e))

// example with parsed schema
generateApi({
name: "ApiModule.ts", // name of output typescript file
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: {
// ...
}
// ...
}
})
.then(sourceFile => fs.writeFile(path, sourceFile))
.catch(e => console.error(e))

```

## 📄 Mass media
Expand Down
16 changes: 14 additions & 2 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ interface GenerateApiParams {
*/
url: string;

/**
* swagger schema JSON
*/
spec: import("swagger-schema-official").Spec;

/**
* default 'api.ts'
*/
Expand Down Expand Up @@ -47,5 +52,12 @@ interface GenerateApiParams {
generateResponses?: boolean;
}

export declare function generateApi(params: Omit<GenerateApiParams, "url">): Promise<string>;
export declare function generateApi(params: Omit<GenerateApiParams, "input">): Promise<string>;
export declare function generateApi(
params: Omit<GenerateApiParams, "url" | "spec">,
): Promise<string>;
export declare function generateApi(
params: Omit<GenerateApiParams, "input" | "spec">,
): Promise<string>;
export declare function generateApi(
params: Omit<GenerateApiParams, "input" | "url">,
): Promise<string>;
12 changes: 11 additions & 1 deletion package-lock.json

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

17 changes: 10 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,24 +1,25 @@
{
"name": "swagger-typescript-api",
"version": "1.11.0",
"version": "1.12.0",
"description": "Create typescript api module from swagger schema",
"scripts": {
"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 --inspect-brk=9229 index.js -p ./swagger-test-cli.json -n swagger-test-cli.ts --union-enums",
"cli:debug:yaml": "node --nolazy --inspect-brk=9229 index.js -p ./swagger-test-cli.yaml -n swagger-test-cli.ts",
"cli:debug:json": "node --nolazy index.js -p ./swagger-test-cli.json -n swagger-test-cli.ts --union-enums",
"cli:debug:yaml": "node --nolazy index.js -p ./swagger-test-cli.yaml -n swagger-test-cli.ts",
"cli:help": "node index.js -h",
"test:all": "npm-run-all generate validate test:routeTypes test:noClient test:defaultAsSuccess test:responses test:templates test:unionEnums --continue-on-error",
"test:all": "npm-run-all generate validate test:routeTypes test:noClient test:defaultAsSuccess test:responses test:templates test:unionEnums test:specProperty --continue-on-error",
"generate": "node tests/generate.js",
"generate:debug": "node --nolazy --inspect-brk=9229 tests/generate.js",
"generate:debug": "node --nolazy tests/generate.js",
"validate": "node tests/validate.js",
"validate:debug": "node --nolazy --inspect-brk=9229 tests/validate.js",
"validate:debug": "node --nolazy tests/validate.js",
"test:routeTypes": "node tests/spec/routeTypes/test.js",
"test:noClient": "node tests/spec/noClient/test.js",
"test:defaultAsSuccess": "node tests/spec/defaultAsSuccess/test.js",
"test:templates": "node tests/spec/templates/test.js",
"test:unionEnums": "node tests/spec/unionEnums/test.js",
"test:responses": "node tests/spec/responses/test.js"
"test:responses": "node tests/spec/responses/test.js",
"test:specProperty": "node tests/spec/specProperty/test.js"
},
"author": "acacode",
"license": "MIT",
Expand All @@ -34,12 +35,14 @@
"typescript": "^3.9.3"
},
"dependencies": {
"@types/swagger-schema-official": "2.0.21",
"axios": "^0.19.2",
"commander": "^5.1.0",
"js-yaml": "^3.13.1",
"lodash": "^4.17.15",
"mustache": "^4.0.1",
"prettier": "^2.0.5",
"swagger-schema-official": "2.0.0-bab6bed",
"swagger2openapi": "^6.0.3"
},
"bin": {
Expand Down
5 changes: 3 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const { parseSchemas } = require("./schema");
const { parseRoutes, groupRoutes } = require("./routes");
const { createApiConfig } = require("./apiConfig");
const { getModelType } = require("./modelTypes");
const { getSwaggerObject, fixSwaggerScheme } = require("./swagger");
const { getSwaggerObject, fixSwaggerScheme, convertSwaggerObject } = require("./swagger");
const { createComponentsMap, filterComponentsMap } = require("./components");
const { createFile, pathIsExist } = require("./files");
const { addToConfig, config } = require("./config");
Expand All @@ -34,6 +34,7 @@ module.exports = {
input,
output,
url,
spec,
name,
templates = resolve(__dirname, config.templates),
generateResponses = config.generateResponses,
Expand All @@ -51,7 +52,7 @@ module.exports = {
templates,
generateUnionEnums,
});
getSwaggerObject(input, url)
(spec ? convertSwaggerObject(spec) : getSwaggerObject(input, url))
.then(({ usageSchema, originalSchema }) => {
const { apiTemplate, clientTemplate, routeTypesTemplate } = getTemplates();

Expand Down
39 changes: 24 additions & 15 deletions src/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,27 +170,36 @@ const convertRouteParamsIntoObject = (params) =>
},
);

const createRequestsMap = (requestInfoByMethodsMap) => {
const parameters = _.get(requestInfoByMethodsMap, "parameters");

return _.reduce(
requestInfoByMethodsMap,
(acc, requestInfo, method) => {
if (method.startsWith("x-") || ["parameters", "$ref"].includes(method)) {
return acc;
}

acc[method] = {
...requestInfo,
parameters: _.compact(_.concat(parameters, requestInfo.parameters)),
};

return acc;
},
{},
);
};

const parseRoutes = ({ paths }, parsedSchemas) =>
_.entries(paths).reduce((routes, [route, requestInfoByMethodsMap]) => {
parameters = _.get(requestInfoByMethodsMap, "parameters");

// TODO: refactor that hell
requestInfoByMethodsMap = _.reduce(
_.omit(requestInfoByMethodsMap, "parameters"),
(acc, requestInfo, method) => {
acc[method] = {
...requestInfo,
parameters: _.compact(_.concat(parameters, requestInfo.parameters)),
};
if (route.startsWith("x-")) return routes;

return acc;
},
{},
);
const requestsMap = createRequestsMap(requestInfoByMethodsMap);

return [
...routes,
..._.map(requestInfoByMethodsMap, (requestInfo, method) => {
..._.map(requestsMap, (requestInfo, method) => {
const {
operationId,
requestBody,
Expand Down
34 changes: 22 additions & 12 deletions src/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ const types = {
// dateTime: "Date",
};

const jsPrimitiveTypes = _.uniq(["number", "string", "boolean"]);
const jsEmptyTypes = _.uniq(["null", "undefined"]);
const formDataTypes = _.uniq([types.file, types.string.binary]);

Expand All @@ -45,8 +46,8 @@ const getTypeAlias = (rawSchema) => {
};

const getInternalSchemaType = (schema) => {
if (schema.enum) return "enum";
if (schema.properties) return "object";
if (!_.isEmpty(schema.enum)) return "enum";
if (!_.isEmpty(schema.properties)) return "object";
if (schema.allOf || schema.oneOf || schema.anyOf || schema.not) return "complex";

return "primitive";
Expand Down Expand Up @@ -75,19 +76,26 @@ const getType = (schema) => {
return primitiveType ? checkAndAddNull(schema, primitiveType) : DEFAULT_PRIMITIVE_TYPE;
};

const isRequired = (property) => {
if (property["x-omitempty"] === false) {
return true;
}

if (config.convertedFromSwagger2) {
return typeof property.nullable === "undefined" ? property.required : !property.nullable;
}
return !!property.required;
};

const getObjectTypeContent = (properties) => {
return _.map(properties, (property, name) => {
const isRequired = config.convertedFromSwagger2
? typeof property.nullable === "undefined"
? property.required
: !property.nullable
: !!property.required;
const required = isRequired(property);
return {
$$raw: property,
description: property.description,
isRequired,
isRequired: required,
field: `${isValidName(name) ? name : `"${name}"`}${
isRequired ? "" : "?"
required ? "" : "?"
}: ${getInlineParseContent(property)}`,
};
});
Expand All @@ -108,7 +116,9 @@ const complexSchemaParsers = {
anyOf: (schema) => {
// T1 | T2 | (T1 & T2)
const combined = _.map(schema.anyOf, complexTypeGetter);
const nonEmptyTypesCombined = combined.filter((type) => !jsEmptyTypes.includes(type));
const nonEmptyTypesCombined = combined.filter(
(type) => !jsEmptyTypes.includes(type) && !jsPrimitiveTypes.includes(type),
);
return checkAndAddNull(
schema,
`${combined.join(" | ")}` +
Expand Down Expand Up @@ -153,9 +163,9 @@ const schemaParsers = {
name: typeName,
description: formatDescription(schema.description),
content: _.map(schema.enum, (key) => ({
key,
key: isIntegerEnum ? key : checkAndRenameModelName(key),
type,
value: isIntegerEnum ? `${key}` : `"${key}"`,
value: key === null ? key : isIntegerEnum ? `${key}` : `"${key}"`,
})),
});
},
Expand Down
Loading

0 comments on commit a163999

Please sign in to comment.