Skip to content

Commit

Permalink
Release 7.0.1 (#215)
Browse files Browse the repository at this point in the history
* fix: use `secure` option from global config (#214)

Fixes #212.

* refactor: logger

* docs: update CHANGELOG

* feat: global `secure` option for `axios` http client

* bump: up version to 7.0.1

Co-authored-by: Danil Kamyshov <[email protected]>
  • Loading branch information
js2me and dkamyshov authored Mar 28, 2021
1 parent 66e02ee commit 8329c4b
Show file tree
Hide file tree
Showing 75 changed files with 440 additions and 99 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# next release

# 7.0.1

Fixes:
- "securityWorker" is only used if "secure" option is specified on each request (issue #212, thanks @dkamyshov)
NOTE: added global `secure` option for `axios` http client
- `index.d.ts` file (add `rawModelTypes`)

# 7.0.0

BREAKING_CHANGES:
Expand Down
2 changes: 1 addition & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ export interface GenerateApiConfiguration {
description: string;
content: string;
}[];
modelTypes: SchemaComponent[];
rawModelTypes: SchemaComponent[];
hasFormDataRoutes: boolean;
hasSecurityRoutes: boolean;
hasQueryRoutes: boolean;
Expand Down
21 changes: 17 additions & 4 deletions package-lock.json

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

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "swagger-typescript-api",
"version": "7.0.0",
"version": "7.0.1",
"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 @@ -57,7 +57,8 @@
"js-yaml": "^4.0.0",
"lodash": "^4.17.21",
"make-dir": "^3.1.0",
"nanoid": "^3.1.20",
"nanoid": "^3.1.22",
"node-emoji": "^1.10.0",
"prettier": "^2.2.1",
"swagger-schema-official": "2.0.0-bab6bed",
"swagger2openapi": "^7.0.5",
Expand Down
9 changes: 4 additions & 5 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const { getTemplates, getTemplatePaths, renderTemplate, getTemplate } = require(
const constants = require("./constants");
const { generateOutputFiles } = require("./output");
const formatFileContent = require("./formatFileContent");
const { eventLog, successLog } = require("./logger");

module.exports = {
constants: constants,
Expand Down Expand Up @@ -86,7 +87,7 @@ module.exports = {

const templatesToRender = getTemplates(config);

if (!config.silent) console.log("☄️ start generating your typescript api");
eventLog("start generating your typescript api");

fixSwaggerScheme(usageSchema, originalSchema);

Expand Down Expand Up @@ -173,17 +174,15 @@ module.exports = {
content: file.declaration.content,
withPrefix: true,
});
if (!config.silent)
console.log(`✔️ your javascript api file created in "${output}"`);
successLog(`javascript api file`, file.name, `created in ${output}`);
} else {
createFile({
path: output,
fileName: file.name,
content: file.content,
withPrefix: true,
});
if (!config.silent)
console.log(`✔️ your typescript api file created in "${output}"`);
successLog(`typescript api file`, file.name, `created in ${output}`);
}

return file;
Expand Down
63 changes: 63 additions & 0 deletions src/logger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
const _ = require("lodash");
const { config } = require("./config");
const { emojify } = require("node-emoji");

/**
*
* @param {"warn" | "log" | "error"} kind
* @param {keyof emoji} emojiName
* @param {...any} messages
* @returns
*/
const createLogMessage = ({ kind, emojiName, messages }) => {
if (config.silent) return;

const emoji = emojify(emojiName);

console[kind](
emoji,
" ",
..._.map(messages, (message) =>
_.startsWith(message, "\n") ? `\n${emoji} ${message.replace(/\n/, "")}` : message,
),
);
};

const log = (...messages) =>
createLogMessage({
kind: "log",
emojiName: ":sparkles:",
messages,
});
const eventLog = (...messages) =>
createLogMessage({
kind: "log",
emojiName: ":comet: ",
messages,
});
const successLog = (...messages) =>
createLogMessage({
kind: "log",
emojiName: ":white_check_mark:",
messages,
});
const warnLog = (...messages) =>
createLogMessage({
kind: "warn",
emojiName: ":warning: ",
messages,
});
const errorLog = (...messages) =>
createLogMessage({
kind: "error",
emojiName: ":exclamation:",
messages,
});

module.exports = {
log,
eventLog,
successLog,
warnLog,
errorLog,
};
4 changes: 2 additions & 2 deletions src/modelNames.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const _ = require("lodash");
const { config } = require("./config");
const { warnLog } = require("./logger");

const isValidName = (name) => /^([A-Za-z$_]{1,})$/g.test(name);

Expand Down Expand Up @@ -28,8 +29,7 @@ const fixModelName = (name) => {

const formatModelName = (name) => {
if (typeof name !== "string") {
if (!config.silent) console.warn("🔨 wrong name of the model name", name);

warnLog("wrong name of the model name", name);
return name;
}

Expand Down
15 changes: 8 additions & 7 deletions src/routeNames.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const { config } = require("./config");
const { warnLog } = require("./logger");
const { renderTemplate } = require("./templates");

const getRouteName = (routeInfo) => {
Expand All @@ -22,13 +23,13 @@ const getRouteName = (routeInfo) => {
duplicateIdentifier,
routeNameDuplicatesMap.get(duplicateIdentifier) + 1,
);
if (!config.silent)
console.warn(
`🥵 Module "${moduleName}" already have method "${routeName}()"`,
`\n🥵 This method has been renamed to "${
routeName + routeNameDuplicatesMap.get(duplicateIdentifier)
}()" to solve conflict names.`,
);

warnLog(
`Module "${moduleName}" already have method "${routeName}()"`,
`\nThis method has been renamed to "${
routeName + routeNameDuplicatesMap.get(duplicateIdentifier)
}()" to solve conflict names.`,
);
} else {
routeNameDuplicatesMap.set(duplicateIdentifier, 1);
}
Expand Down
3 changes: 2 additions & 1 deletion src/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const { config } = require("./config");
const { nanoid } = require("nanoid");
const { getRouteName } = require("./routeNames");
const { createComponent } = require("./components");
const { warnLog } = require("./logger");

const formDataTypes = _.uniq([types.file, types.string.binary]);

Expand Down Expand Up @@ -132,7 +133,7 @@ const parseRoute = (route) => {
if (!paramName) return pathParams;

if (_.includes(paramName, "-")) {
if (!config.silent) console.warn("🔨 wrong path param name", paramName);
warnLog("wrong path param name", paramName);
}

return [
Expand Down
5 changes: 3 additions & 2 deletions src/swagger.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const converter = require("swagger2openapi");
const https = require("https");
const { addToConfig, config } = require("./config");
const { pathIsExist, getFileContent } = require("./files");
const { log } = require("./logger");

const parseSwaggerFile = (file) => {
if (typeof file !== "string") return file;
Expand All @@ -19,10 +20,10 @@ const parseSwaggerFile = (file) => {
const getSwaggerFile = (pathToSwagger, urlToSwagger, disableStrictSSL) =>
new Promise((resolve) => {
if (pathIsExist(pathToSwagger)) {
if (!config.silent) console.log(`try to get swagger by path "${pathToSwagger}"`);
log(`try to get swagger by path "${pathToSwagger}"`);
resolve(getFileContent(pathToSwagger));
} else {
if (!config.silent) console.log(`try to get swagger by url "${urlToSwagger}"`);
log(`try to get swagger by url "${urlToSwagger}"`);
let agent = undefined;
if (disableStrictSSL) {
agent = new https.Agent({
Expand Down
13 changes: 6 additions & 7 deletions src/templates.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const Eta = require("eta");
const { getFileContent, pathIsExist } = require("./files");
const { config } = require("./config");
const { resolve } = require("path");
const { warnLog, log } = require("./logger");

/**
* name - project template name,
Expand Down Expand Up @@ -56,11 +57,10 @@ const getTemplate = ({ fileName, name, path }) => {
if (pathIsExist(baseFullPath)) {
fileContent = getFileContent(baseFullPath);
} else {
if (!config.silent)
console.log(
`❗❗❗ ${_.lowerCase(name)} template not found in ${customFullPath}\n` +
`Code generator will use the default template`,
);
warnLog(
`${_.lowerCase(name)} template not found in ${customFullPath}`,
`\nCode generator will use the default template`,
);
}

if (pathIsExist(originalFullPath)) {
Expand All @@ -72,8 +72,7 @@ const getTemplate = ({ fileName, name, path }) => {
};

const getTemplates = ({ templatePaths }) => {
if (!config.silent)
console.log(`✨ try to read templates from directory "${templatePaths.custom}"`);
log(`try to read templates from directory "${templatePaths.custom}"`);

const templatesMap = _.reduce(
TEMPLATE_INFOS,
Expand Down
7 changes: 5 additions & 2 deletions templates/base/http-clients/axios-http-client.eta
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export type RequestParams = Omit<FullRequestParams, "body" | "method" | "query"

export interface ApiConfig<SecurityDataType = unknown> extends Omit<AxiosRequestConfig, "data" | "cancelToken"> {
securityWorker?: (securityData: SecurityDataType | null) => Promise<AxiosRequestConfig | void> | AxiosRequestConfig | void;
secure?: boolean;
}

export enum ContentType {
Expand All @@ -37,9 +38,11 @@ export class HttpClient<SecurityDataType = unknown> {
private instance: AxiosInstance;
private securityData: SecurityDataType | null = null;
private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"];
private secure?: boolean;

constructor({ securityWorker, ...axiosConfig }: ApiConfig<SecurityDataType> = {}) {
constructor({ securityWorker, secure, ...axiosConfig }: ApiConfig<SecurityDataType> = {}) {
this.instance = axios.create({ ...axiosConfig, baseURL: axiosConfig.baseURL || "<%~ apiConfig.baseUrl %>" })
this.secure = secure;
this.securityWorker = securityWorker;
}

Expand Down Expand Up @@ -69,7 +72,7 @@ export class HttpClient<SecurityDataType = unknown> {
body,
...params
}: FullRequestParams): Promise<AxiosResponse<T>> => {
const secureParams = (secure && this.securityWorker && (await this.securityWorker(this.securityData))) || {};
const secureParams = ((typeof secure === 'boolean' ? secure : this.secure) && this.securityWorker && (await this.securityWorker(this.securityData))) || {};
const requestParams = this.mergeRequestParams(params, secureParams);

return this.instance.request({
Expand Down
2 changes: 1 addition & 1 deletion templates/base/http-clients/fetch-http-client.eta
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ export class HttpClient<SecurityDataType = unknown> {
cancelToken,
...params
}: FullRequestParams): Promise<HttpResponse<T, E>> => {
const secureParams = (secure && this.securityWorker && await this.securityWorker(this.securityData)) || {};
const secureParams = ((typeof secure === 'boolean' ? secure : this.baseApiParams.secure) && this.securityWorker && await this.securityWorker(this.securityData)) || {};
const requestParams = this.mergeRequestParams(params, secureParams);
const queryString = query && this.toQueryString(query);
const payloadFormatter = this.contentFormatters[type || ContentType.Json];
Expand Down
6 changes: 5 additions & 1 deletion tests/generated/v2.0/adafruit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,11 @@ export class HttpClient<SecurityDataType = unknown> {
cancelToken,
...params
}: FullRequestParams): Promise<HttpResponse<T, E>> => {
const secureParams = (secure && this.securityWorker && (await this.securityWorker(this.securityData))) || {};
const secureParams =
((typeof secure === "boolean" ? secure : this.baseApiParams.secure) &&
this.securityWorker &&
(await this.securityWorker(this.securityData))) ||
{};
const requestParams = this.mergeRequestParams(params, secureParams);
const queryString = query && this.toQueryString(query);
const payloadFormatter = this.contentFormatters[type || ContentType.Json];
Expand Down
6 changes: 5 additions & 1 deletion tests/generated/v2.0/another-example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,11 @@ export class HttpClient<SecurityDataType = unknown> {
cancelToken,
...params
}: FullRequestParams): Promise<HttpResponse<T, E>> => {
const secureParams = (secure && this.securityWorker && (await this.securityWorker(this.securityData))) || {};
const secureParams =
((typeof secure === "boolean" ? secure : this.baseApiParams.secure) &&
this.securityWorker &&
(await this.securityWorker(this.securityData))) ||
{};
const requestParams = this.mergeRequestParams(params, secureParams);
const queryString = query && this.toQueryString(query);
const payloadFormatter = this.contentFormatters[type || ContentType.Json];
Expand Down
6 changes: 5 additions & 1 deletion tests/generated/v2.0/another-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,11 @@ export class HttpClient<SecurityDataType = unknown> {
cancelToken,
...params
}: FullRequestParams): Promise<HttpResponse<T, E>> => {
const secureParams = (secure && this.securityWorker && (await this.securityWorker(this.securityData))) || {};
const secureParams =
((typeof secure === "boolean" ? secure : this.baseApiParams.secure) &&
this.securityWorker &&
(await this.securityWorker(this.securityData))) ||
{};
const requestParams = this.mergeRequestParams(params, secureParams);
const queryString = query && this.toQueryString(query);
const payloadFormatter = this.contentFormatters[type || ContentType.Json];
Expand Down
6 changes: 5 additions & 1 deletion tests/generated/v2.0/api-with-examples.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,11 @@ export class HttpClient<SecurityDataType = unknown> {
cancelToken,
...params
}: FullRequestParams): Promise<HttpResponse<T, E>> => {
const secureParams = (secure && this.securityWorker && (await this.securityWorker(this.securityData))) || {};
const secureParams =
((typeof secure === "boolean" ? secure : this.baseApiParams.secure) &&
this.securityWorker &&
(await this.securityWorker(this.securityData))) ||
{};
const requestParams = this.mergeRequestParams(params, secureParams);
const queryString = query && this.toQueryString(query);
const payloadFormatter = this.contentFormatters[type || ContentType.Json];
Expand Down
Loading

0 comments on commit 8329c4b

Please sign in to comment.