Skip to content

Commit

Permalink
Merge pull request #17 from ProtocolNebula/issue/2-settings-improvement
Browse files Browse the repository at this point in the history
Issue/2 settings improvement
  • Loading branch information
ProtocolNebula authored Jan 9, 2021
2 parents 0c133de + abd552a commit 0ce5221
Show file tree
Hide file tree
Showing 11 changed files with 139 additions and 47 deletions.
2 changes: 1 addition & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/src/main.ts",
"program": "${workspaceFolder}/src/cli.ts",
"preLaunchTask": "tsc: build - tsconfig.json",
"args": [
"-f",
Expand Down
45 changes: 37 additions & 8 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
- [Installation](#installation)
- [Usage](#usage)
- [The script](#the-script)
- [Config file](#config-file)
- [Create the config file (you choose the name and the location)](#create-the-config-file-you-choose-the-name-and-the-location)
- [Launch the script](#launch-the-script)
- [Main CLI commands](#main-cli-commands)
- [Development](#development)
- [Run with watch (internet file)](#run-with-watch-internet-file)
Expand Down Expand Up @@ -46,25 +49,51 @@ Is recommended to add a script to your `package.json` or package manager that yo
transform-swagger -f URI/TO/SWAGGER/JSON/OR/YAML -o src/generatedApi/ -t angular2
```

### Config file

> The settings of the config file are the same than cli one (but in `camelCase`).
#### Create the config file (you choose the name and the location)

We will name for example `transfrom-config.json`

```json
{
"clean": true,
"file": "./examples/openApiFiles/passportescaperoom.com.json",
"outputFolder": "./examples/generated/angular2",
"template": "angular2",
"saveFile": "./openApiFiles/passportescaperoom.com"
}
```

#### Launch the script

```bash
transform-swagger config-file ./examples/transform-config.json
```

### Main CLI commands

```bash
Usage: transform-swagger [options]

Options:
--version, -v Show version number [boolean]
--version, -v Show version number [boolean]
--config-file Configuration file to use (values from cli will overwrite
the files one).
--clean No clean the output-folder, so old files will remain
[boolean] [default: true]
-f, --file Path OR URL to the swagger document to parse
[required]
[boolean] [default: true]
-f, --file Path OR URL to the swagger document to parse [required]
-o, --output-folder Specify the output folder (generated folders will be
replaced) [default: "output"]
replaced) [default: "output"]
-t, --template Template (preset) name or path to a template
-h, --help Show help [boolean]
-h, --help Show help [boolean]
-s, --save-file [default: "./openapi_temp"]

Examples:
transform-swagger -f swagger.js -o Convert a Swagger JSON file to
api/ -t angular2 compatible-angular API
cli -f swagger.js -o api/ -t angular2 Convert a Swagger JSON file to
compatible-angular API
```

## Development
Expand Down
2 changes: 2 additions & 0 deletions examples/Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ You can also try to use `the original files` from each source or test with `your
**Local file command:**
```bash
npm start -- -f examples/openApiFiles/passportescaperoom.com.json -o examples/generated/angular2 -t angular2
# OR
npm start -- config-file ./examples/transform-config.json
```

**Generate from url**
Expand Down
7 changes: 7 additions & 0 deletions examples/transform-config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"clean": true,
"file": "./examples/openApiFiles/passportescaperoom.com.json",
"outputFolder": "./examples/generated/angular2",
"template": "angular2",
"saveFile": "./openApiFiles/passportescaperoom.com"
}
2 changes: 1 addition & 1 deletion nodemon.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
"watch": ["src", "templates"],
"ext": "ts,json",
"ignore": ["src/**/*.spec.ts"],
"exec": "npx ts-node ./src/main.ts"
"exec": "npx ts-node ./src/cli.ts"
}
12 changes: 6 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,17 @@
"time-saver",
"tool"
],
"main": "dist/main.js",
"types": "dist/main.d.ts",
"main": "dist/cli",
"types": "dist/cli.d.ts",
"scripts": {
"prepublish": "npm run build",
"start": "ts-node src/main.ts",
"start": "ts-node src/cli",
"start:dev": "npx nodemon",
"start:build": "node build/index.js",
"start:webpack": "npx webpack --watch",
"build": "tsc",
"build:webpack": "npx webpack --mode production",
"generate:examples": "npm start -- -f examples/openApiFiles/passportescaperoom.com.json -o examples/generated/angular2 -t angular2",
"generate:examples": "npm start -- --config-file ./examples/transform-config.json",
"test": "echo \"Error: no test specified\" && exit 1"
},
"license": "ISC",
Expand All @@ -44,7 +44,7 @@
"url": "https://patreon.com/ProtocolNebula"
},
"bin": {
"transform-swagger": "./cli.js"
"transform-swagger": "./build/cli.js"
},
"homepage": "https://github.com/ProtocolNebula/ts-openapi-generator",
"repository": {
Expand Down Expand Up @@ -79,7 +79,7 @@
"husky": {
"hooks": {
"pre-commit": "pretty-quick --staged",
"pre-push": "npm run generate:examples && git add examples/ && (git commit -m 'Updated examples' || return 0)"
"pre-push": "npm run generate:examples && (git add examples/ && git commit -m 'Updated examples' || echo 'No example changes')"
}
}
}
15 changes: 15 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env node
import { config } from './models/config.model';
import { argumentsInstance } from './services/arguments.service';
import { generateAPIFiles } from './main';

config.parseYargs(argumentsInstance);
// FOLDERS INFORMATION
console.info('Output folders:');
console.table({
OUTPUT_PATH: config.outputPath,
BASE_FOLDER: config.exportPath,
MODELS: config.exportPath,
APIS: config.exportPath,
});
generateAPIFiles(config);
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './models/config.model';
export * from './main';
24 changes: 5 additions & 19 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,29 @@
import * as fs from 'fs-extra';
import { config } from './models/config.model';
import { argumentsInstance } from './services/arguments.service';
import { config, ConfigI } from './models/config.model';
import { FileReaderService } from './services/parsers/file-reader.service';
import { APIParserService } from './services/parsers/open-api-v3/api-parser.service';
import { ComponentsParserService } from './services/parsers/open-api-v3/components-parser.service';
import { ApiWritterService } from './services/writters/api-writter.service';
import { ModelWritterService } from './services/writters/model-writter.service';
import { Store } from './stores/entities.store';

config.parseYargs(argumentsInstance);

// FOLDERS INFORMATION
console.info('Output folders:');
console.table({
OUTPUT_PATH: config.outputPath,
BASE_FOLDER: config.exportPath,
MODELS: config.exportPath,
APIS: config.exportPath,
});

// Read the file
async function run() {
export async function generateAPIFiles(config: ConfigI) {
try {
// Check if the template does not exist
config.templatePath;

console.log('');
if (argumentsInstance.clean) {
if (config.cleanFolder) {
console.log('Removing previously generated data...');
fs.removeSync(config.exportPath);
} else {
console.log('no-clean flag recevived, clean folder skipped');
}
console.log('');

console.log('Opening file:', argumentsInstance.file);
const fileParser = new FileReaderService(argumentsInstance.file, config);
console.log('Opening file:', config.fileURI);
const fileParser = new FileReaderService(config.fileURI, config);
console.log('Parsing file...');
console.log('');
const documentParsed = await fileParser.readFile();
Expand Down Expand Up @@ -68,5 +56,3 @@ async function run() {
console.error('Application stopped');
}
}

run();
53 changes: 45 additions & 8 deletions src/models/config.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,17 @@ import { resolve as pathResolve } from 'path';
import { TemplateConfigModel } from './template-config.model';

export interface ConfigI {
tempFilePath: string;
cleanFolder: boolean;
fileURI: string;
outputPath: string;
tempFilePath: string;
template: string;

readonly exportPath: string;
readonly outputModelsPath: string;
readonly outputApisPath: string;
template: string;
readonly outputModelsPath: string;
readonly templateConfig: TemplateConfigModel;
readonly templatePath;
}

class ConfigModel implements ConfigI {
Expand All @@ -23,9 +27,15 @@ class ConfigModel implements ConfigI {
private _templatePath: string;
private _templateConfig: TemplateConfigModel;

fileURI: string;
cleanFolder: boolean;

get outputPath(): string {
return this._outputPath;
}
set outputPath(outputPath: string) {
this._outputPath = pathResolve(outputPath);
}

get exportPath(): string {
return pathResolve(this.outputPath, this._outputBaseFolder);
Expand All @@ -44,7 +54,7 @@ class ConfigModel implements ConfigI {
}

set tempFilePath(tempFilePath: string) {
this._tempFilePath = tempFilePath;
this._tempFilePath = pathResolve(tempFilePath);
}

get template(): string {
Expand Down Expand Up @@ -85,17 +95,44 @@ class ConfigModel implements ConfigI {

get templateConfig(): TemplateConfigModel {
if (!this._templateConfig) {
this._templateConfig = new TemplateConfigModel(pathResolve(this.templatePath, 'config'));
this._templateConfig = new TemplateConfigModel(
pathResolve(this.templatePath, 'config'),
);
}
return this._templateConfig;
}

constructor() {}

setConfig(config: ConfigI) {
for (const key in config) {
const value = config[key];
if (value) {
this[key] = value;
} else {
console.warn(`${key} in config not recognized`);
}
}
}

parseYargs(yargs): void {
this._outputPath = yargs.outputFolder;
this.tempFilePath = pathResolve(yargs.saveFile);
this.template = yargs.template;
const config = {} as ConfigI;
if (yargs.saveFile) {
config.tempFilePath = yargs.saveFile;
}
if (yargs.file) {
config.fileURI = yargs.file;
}
if (yargs.template) {
config.template = yargs.template;
}
if (yargs.outputFolder) {
config.outputPath = yargs.outputFolder;
}
if (this.cleanFolder === undefined || yargs.clean === false) {
config.cleanFolder = yargs.clean;
}
this.setConfig(config);
}
}

Expand Down
22 changes: 18 additions & 4 deletions src/services/arguments.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as yargs from 'yargs';
import { readFileSync } from 'fs';

export const argumentsInstance = yargs
.alias('version', 'v')
Expand All @@ -9,9 +10,21 @@ export const argumentsInstance = yargs
'Convert a Swagger JSON file to compatible-angular API',
)

.config('config-file', (configPath) => {
return JSON.parse(readFileSync(configPath, 'utf-8'));
})
.describe(
'config-file',
'Configuration file to use (values from cli will overwrite the files one).',
)
.default('save-file', './openapi_temp')

.nargs('save-file', 1)
.alias('s', 'file')
.describe('file', 'Path to save the file IF --file IS AN URL (without extension)')
.alias('s', 'save-file')
.describe(
'file',
'Path to save the file IF --file IS AN URL (without extension)',
)
.default('save-file', './openapi_temp')

.nargs('file', 1)
Expand Down Expand Up @@ -41,5 +54,6 @@ export const argumentsInstance = yargs
.help('help')
.alias('h', 'help')

.epilog('For more info visit: https://github.com/ProtocolNebula/ts-openapi-generator/')
.argv;
.epilog(
'For more info visit: https://github.com/ProtocolNebula/ts-openapi-generator/',
).argv;

0 comments on commit 0ce5221

Please sign in to comment.