Skip to content

Commit d79c9cd

Browse files
committed
refactor(): lint errors and some functions moved from helpers
Signed-off-by: Vojtech Mašek <[email protected]>
1 parent 369b560 commit d79c9cd

File tree

4 files changed

+33
-33
lines changed

4 files changed

+33
-33
lines changed

src/generator.ts

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@ import { ensureDir } from 'fs-extra';
33
import * as Mustache from 'mustache';
44
import { dirname, join } from 'path';
55
import { parse as swaggerFile, validate } from 'swagger-parser';
6+
import { Operation, Path, Spec as Swagger } from 'swagger-schema-official';
67
import { promisify } from 'util';
78
import { MustacheData, GenOptions, Definition } from './types';
8-
import { fileName, logWarn, dashCase, getAllSwaggerTags, flattenAll, compareStringByKey } from './helper';
9+
import { fileName, logWarn, dashCase, flattenAll, compareStringByKey } from './helper';
910
import { createMustacheViewModel } from './parser';
1011

1112
const ALL_TAGS_OPTION = 'all';
@@ -31,8 +32,8 @@ export async function generateAPIClient(options: GenOptions): Promise<string[]>
3132
throw new Error(`Provided swagger file "${swaggerFilePath}" is invalid`);
3233
}
3334

34-
const swaggerDef = await swaggerFile(swaggerFilePath);
35-
const allTags = getAllSwaggerTags(swaggerDef);
35+
const swaggerDef: Swagger = await swaggerFile(swaggerFilePath);
36+
const allTags = getAllSwaggerTags(swaggerDef.paths);
3637
const specifiedTags = options.splitPathTags || [];
3738
const usedTags: (string | undefined)[] = specifiedTags.length === 0
3839
? [undefined]
@@ -46,7 +47,7 @@ export async function generateAPIClient(options: GenOptions): Promise<string[]>
4647
const allDefinitions = apiTagsData.map(({definitions}) => definitions).reduce<Definition[]>(
4748
(acc, definitions) => [...acc, ...definitions], []
4849
)
49-
.sort(compareStringByKey('name'))
50+
.sort(compareStringByKey('name')) // tslint:disable-line:no-array-mutation
5051
.filter(({name}, index, self) => index > 0 ? name !== self[index - 1].name : true);
5152

5253
return flattenAll([
@@ -134,3 +135,14 @@ async function generateModuleExportIndex(viewContext: MustacheData, outputPath:
134135
await promisify(writeFile)(outfile, result, 'utf-8');
135136
return [outfile];
136137
}
138+
139+
export function getAllSwaggerTags(paths: { [pathName: string]: Path }): string[] {
140+
const allTags = Object.values(paths).map((pathDef) =>
141+
// get tags from all the paths and flatten with reduce
142+
Object.values(pathDef)
143+
.map(({tags}: Operation) => tags || [])
144+
.reduce<string[]>((acc, tags) => [...acc, ...tags], [])
145+
).reduce<string[]>((acc, tags) => [...acc, ...tags], []); // array of tags fatten with reduce
146+
147+
return Array.from(new Set(allTags));
148+
}

src/helper.ts

Lines changed: 0 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import { Spec as Swagger, Path, Operation } from 'swagger-schema-official';
21
import { FileInfix } from './types';
32

43
export const BASIC_TS_TYPE_REGEX = /\b(?:string|number|integer|boolean)\b/;
@@ -87,20 +86,6 @@ export function prefixImportedModels(type: string = ''): string {
8786
return BUILD_IN_TS_TYPE_REGEX.test(type) ? type : `models.${type}`;
8887
}
8988

90-
export function determineDomain({schemes, host, basePath}: Swagger): string {
91-
92-
// if the host is defined then try and use a protocol from the swagger file
93-
// otherwise use the current protocol of loaded app
94-
const protocol = host && schemes && schemes.length > 0 ? `${schemes[0]}://` : '//';
95-
96-
// if no host exists in the swagger file use a window location relative path
97-
const domain = host
98-
? host // tslint:disable-next-line:no-invalid-template-strings
99-
: '${window.location.hostname}${window.location.port ? \':\'+window.location.port : \'\'}';
100-
const base = ('/' === basePath || !basePath ? '' : basePath);
101-
return `${protocol}${domain}${base}`;
102-
}
103-
10489
export function replaceNewLines(str: string = '', replaceValue: string = ''): string {
10590
return str.replace(/(\r\n|\r|\n)/g, replaceValue);
10691
}
@@ -109,16 +94,6 @@ export function logWarn(str: string): void {
10994
console.warn('\x1b[33m%s\x1b[0m', str);
11095
}
11196

112-
export function getAllSwaggerTags(swagger: Swagger): string[] {
113-
const allTags: string[] = [];
114-
Object.values(swagger.paths)
115-
.forEach((pathDef: Path) =>
116-
Object.values(pathDef).forEach((operation: Operation) =>
117-
allTags.push(...(operation.tags ? operation.tags : [])))
118-
);
119-
return Array.from(new Set(allTags));
120-
}
121-
12297
/**
12398
* Aggregates an array of promises of arrays to a single promise of a flattened array.
12499
* @param promises An array of promises that resolve to arrays of values.
@@ -128,7 +103,6 @@ export async function flattenAll<T>(promises: Promise<T[]>[]): Promise<T[]> {
128103
return Array.prototype.concat(...await Promise.all(promises));
129104
}
130105

131-
132106
export function compareStringByKey<T>(key: keyof T): (a: T, b: T) => number {
133107
return (a, b) => a[key] && b[key] ? `${a[key]}`.localeCompare(`${b[key]}`) : -1;
134108
}

src/parser.ts

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ import {
2020
BASIC_TS_TYPE_REGEX,
2121
toCamelCase,
2222
dereferenceType,
23-
determineDomain,
2423
fileName,
2524
prefixImportedModels,
2625
replaceNewLines,
@@ -71,6 +70,20 @@ export function createMustacheViewModel(swagger: Swagger, swaggerTag?: string):
7170
};
7271
}
7372

73+
export function determineDomain({schemes, host, basePath}: Swagger): string {
74+
75+
// if the host is defined then try and use a protocol from the swagger file
76+
// otherwise use the current protocol of loaded app
77+
const protocol = host && schemes && schemes.length > 0 ? `${schemes[0]}://` : '//';
78+
79+
// if no host exists in the swagger file use a window location relative path
80+
const domain = host
81+
? host // tslint:disable-next-line:no-invalid-template-strings
82+
: '${window.location.hostname}${window.location.port ? \':\'+window.location.port : \'\'}';
83+
const base = ('/' === basePath || !basePath ? '' : basePath);
84+
return `${protocol}${domain}${base}`;
85+
}
86+
7487
function parseMethods({paths, security, parameters}: Swagger, swaggerTag?: string): Method[] {
7588
const supportedMethods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT'];
7689

@@ -218,7 +231,7 @@ function parseInterfaceProperties(properties: { [propertyName: string]: Schema }
218231
typescriptType,
219232
};
220233
}
221-
).sort(compareStringByKey('name'));
234+
).sort(compareStringByKey('name')); // tslint:disable-line:no-array-mutation
222235
}
223236

224237
function parseReference(schema: Schema): string {
@@ -276,7 +289,7 @@ function defineInterface(schema: Schema, definitionKey: string): Definition {
276289
.map(({type}) => type || '')
277290
.filter((type) => type !== name)
278291
.concat(extendInterface ? [extendInterface] : [])
279-
.sort()
292+
.sort() // tslint:disable-line:no-array-mutation
280293
// filter duplicate imports
281294
.filter((el, i, a) => (i === a.indexOf(el)) ? 1 : 0),
282295
isEnum: false,

tslint.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@
128128
],
129129
"no-misused-new": true,
130130
"no-namespace": true,
131+
"no-array-mutation": true,
131132
"no-object-mutation": [true, {"ignore-prefix": "this."}],
132133
"no-parameter-reassignment": false,
133134
"no-reference": true,

0 commit comments

Comments
 (0)