Skip to content

Commit 46efafb

Browse files
committed
Configure CLI Program
* Original function removed * Added 2 commands to program * Init tsc project inside bin
1 parent 645af30 commit 46efafb

File tree

9 files changed

+281
-63
lines changed

9 files changed

+281
-63
lines changed

bin/bin_test.sh

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
tsc \
2+
&& chmod +x ./bin.js \
3+
&& ./bin.js
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { writeFile } from "../../../src/utils/fileSystem";
2+
import { HttpClient } from "../../../src/HttpClient";
3+
import { StructuredOptions } from "../from_spec";
4+
5+
export const generateDefaultConfig = async (path) => {
6+
console.log('Generating default files to: ', path);
7+
const default_config = getDefaultConfig();
8+
const raw_string = JSON.stringify(default_config, undefined, 2);
9+
await writeFile(path, raw_string);
10+
}
11+
12+
function getDefaultConfig (): StructuredOptions {
13+
return {
14+
input: './api-specification',
15+
output: './generated',
16+
httpClient: HttpClient.FETCH,
17+
options: {
18+
useOptions: false,
19+
useUnionTypes: false,
20+
},
21+
export_options: {
22+
exportCore: true,
23+
exportServices: true,
24+
exportModels: true,
25+
exportSchemas: false,
26+
},
27+
// write: false,
28+
// request: false,
29+
};
30+
}

bin/commands/from_spec.ts

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import { Command } from "commander";
2+
import { generateDefaultConfig } from "./FromSpec/generateDefaultConfig";
3+
4+
const file_name = 'oas-config';
5+
export const default_config_path = `./${file_name}.json`;
6+
7+
interface FromSpecParameters {
8+
path: string;
9+
generate: boolean;
10+
}
11+
12+
export interface StructuredOptions {
13+
input: string;
14+
output: string;
15+
httpClient;
16+
options: {
17+
useOptions?: boolean;
18+
useUnionTypes?: boolean;
19+
}
20+
export_options: {
21+
exportCore?: boolean;
22+
exportControllers?: boolean;
23+
exportServices?: boolean;
24+
exportModels?: boolean;
25+
exportSchemas?: boolean;
26+
};
27+
}
28+
29+
30+
export const FromSpec = new Command()
31+
.name('FromSpec')
32+
.usage('[spec-options]')
33+
.option('-p, --path <value>', 'Path of configuration file', default_config_path)
34+
.option(`--generate`, 'Generate default configuration file', false)
35+
.action(async ({path, generate}: FromSpecParameters) => {
36+
if (generate) {
37+
await generateDefaultConfig(path);
38+
} else {
39+
analyzeControllers();
40+
}
41+
});
42+
43+
44+
function analyzeControllers() {
45+
46+
}

bin/commands/generation.ts

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import { Command } from "commander";
2+
import { default_config_path, StructuredOptions } from "./from_spec";
3+
import { existsSync, readFileSync } from "fs";
4+
import { resolve } from "path";
5+
import { GenerationOptions } from "../../src/types/default";
6+
7+
const pkg = require('../../package.json');
8+
9+
export const generation = new Command()
10+
.name('generate_files')
11+
.usage('[options]')
12+
.version(pkg.version)
13+
.option('-i, --input <value>', 'OpenAPI specification, can be a path, url or string content (required)')
14+
.option('-o, --output <value>', 'Output directory (required)')
15+
.option('-f, --config [path]', 'Generate by config file (required)')
16+
.option('-c, --client <value>', 'HTTP client to generate [fetch, xhr, node]', 'fetch')
17+
.option('--useOptions', 'Use options instead of arguments')
18+
.option('--useUnionTypes', 'Use union types instead of enums')
19+
.option('--exportCore <value>', 'Write core files to disk', true)
20+
.option('--exportServices <value>', 'Write services to disk', true)
21+
.option('--exportModels <value>', 'Write models to disk', true)
22+
.option('--exportSchemas <value>', 'Write schemas to disk', false)
23+
.option('--request <value>', 'Path to custom request file')
24+
// .parse(process.argv)
25+
// .opts();
26+
.action(async (params) => {
27+
let generation_setting: GenerationOptions;
28+
if (params.config) {
29+
const x: StructuredOptions = await get_config(params.config === true ? default_config_path : params.config);
30+
generation_setting = {
31+
input: x.input,
32+
output: x.output,
33+
httpClient: x.httpClient,
34+
useOptions: x.options.useOptions,
35+
useUnionTypes: x.options.useUnionTypes,
36+
exportCore: x.export_options.exportCore,
37+
exportServices: x.export_options.exportServices,
38+
exportModels: x.export_options.exportModels,
39+
exportSchemas: x.export_options.exportSchemas,
40+
}
41+
} else if (params.input && params.output) {
42+
generation_setting = {
43+
input: params.input,
44+
output: params.output,
45+
httpClient: params.client,
46+
useOptions: params.useOptions,
47+
useUnionTypes: params.useUnionTypes,
48+
exportCore: JSON.parse(params.exportCore) === true,
49+
exportServices: JSON.parse(params.exportServices) === true,
50+
exportModels: JSON.parse(params.exportModels) === true,
51+
exportSchemas: JSON.parse(params.exportSchemas) === true,
52+
request: params.request,
53+
};
54+
} else {
55+
throw new Error('DEFINE PLS');
56+
}
57+
58+
const OpenAPI = require(resolve(__dirname, '../../dist/index.js'));
59+
OpenAPI.generate(generation_setting)
60+
.then(() => {
61+
process.exit(0);
62+
})
63+
.catch(error => {
64+
console.error(error);
65+
process.exit(1);
66+
});
67+
68+
// const OpenAPI = require(resolve(__dirname, '../dist/index.js'));
69+
//
70+
// if (OpenAPI) {
71+
// OpenAPI.generate({
72+
// input: params.input,
73+
// output: params.output,
74+
// httpClient: params.client,
75+
// useOptions: params.useOptions,
76+
// useUnionTypes: params.useUnionTypes,
77+
// exportCore: JSON.parse(params.exportCore) === true,
78+
// exportServices: JSON.parse(params.exportServices) === true,
79+
// exportModels: JSON.parse(params.exportModels) === true,
80+
// exportSchemas: JSON.parse(params.exportSchemas) === true,
81+
// request: params.request,
82+
// })
83+
// .then(() => {
84+
// process.exit(0);
85+
// })
86+
// .catch(error => {
87+
// console.error(error);
88+
// process.exit(1);
89+
// });
90+
// }
91+
});
92+
93+
94+
const get_config = async (spec_path: string): Promise<StructuredOptions> => {
95+
if (!existsSync(spec_path)) {
96+
throw new Error(`File not found @ ${spec_path}`);
97+
}
98+
99+
return JSON.parse(
100+
readFileSync(spec_path, {encoding: "utf8"})
101+
);
102+
};

bin/index.js

Lines changed: 0 additions & 48 deletions
This file was deleted.

bin/index.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#!/usr/bin/env node
2+
3+
'use strict';
4+
5+
import {program} from 'commander';
6+
import { FromSpec } from "./commands/from_spec";
7+
import { generation } from "./commands/generation";
8+
9+
program
10+
.name('OpenApi')
11+
.usage('<command> [options]')
12+
.addCommand(generation)
13+
.addCommand(FromSpec)
14+
.parse(process.argv);
15+

bin/tsconfig.json

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
{
2+
"compilerOptions": {
3+
/* Basic Options */
4+
// "incremental": true, /* Enable incremental compilation */
5+
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
6+
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
7+
// "lib": [], /* Specify library files to be included in the compilation. */
8+
// "allowJs": true, /* Allow javascript files to be compiled. */
9+
// "checkJs": true, /* Report errors in .js files. */
10+
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
11+
// "declaration": true, /* Generates corresponding '.d.ts' file. */
12+
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
13+
// "sourceMap": true, /* Generates corresponding '.map' file. */
14+
// "outFile": "./", /* Concatenate and emit output to single file. */
15+
// "outDir": "./", /* Redirect output structure to the directory. */
16+
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
17+
// "composite": true, /* Enable project compilation */
18+
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
19+
// "removeComments": true, /* Do not emit comments to output. */
20+
// "noEmit": true, /* Do not emit outputs. */
21+
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
22+
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
23+
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
24+
25+
/* Strict Type-Checking Options */
26+
"strict": true, /* Enable all strict type-checking options. */
27+
"noImplicitAny": false, /* Raise error on expressions and declarations with an implied 'any' type. */
28+
// "strictNullChecks": true, /* Enable strict null checks. */
29+
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
30+
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
31+
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
32+
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
33+
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
34+
35+
/* Additional Checks */
36+
// "noUnusedLocals": true, /* Report errors on unused locals. */
37+
// "noUnusedParameters": true, /* Report errors on unused parameters. */
38+
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
39+
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
40+
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
41+
42+
/* Module Resolution Options */
43+
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
44+
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
45+
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
46+
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
47+
// "typeRoots": [], /* List of folders to include type definitions from. */
48+
// "types": [], /* Type declaration files to be included in compilation. */
49+
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
50+
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
51+
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
52+
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
53+
54+
/* Source Map Options */
55+
// "sourceRoot": "", /* Specify the ___location where debugger should locate TypeScript files instead of source locations. */
56+
// "mapRoot": "", /* Specify the ___location where debugger should locate map files instead of generated locations. */
57+
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
58+
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
59+
60+
/* Experimental Options */
61+
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
62+
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
63+
64+
/* Advanced Options */
65+
"skipLibCheck": true, /* Skip type checking of declaration files. */
66+
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
67+
}
68+
}

src/index.ts

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -10,23 +10,10 @@ import { writeClient } from './utils/writeClient';
1010
import { Client } from "./client/interfaces/Client";
1111
import { OpenApi as OpenApiV3 } from "./openApi/v3/interfaces/OpenApi";
1212
import { OpenApi as OpenApiV2 } from "./openApi/v2/interfaces/OpenApi";
13+
import { GenerationOptions } from "./types/default";
1314

1415
export { HttpClient } from './HttpClient';
1516

16-
export type Options = {
17-
input: string | Record<string, any>;
18-
output: string;
19-
httpClient?: HttpClient;
20-
useOptions?: boolean;
21-
useUnionTypes?: boolean;
22-
exportCore?: boolean;
23-
exportServices?: boolean;
24-
exportModels?: boolean;
25-
exportSchemas?: boolean;
26-
request?: string;
27-
write?: boolean;
28-
};
29-
3017
/**
3118
* Generate the OpenAPI client. This method will read the OpenAPI specification and based on the
3219
* given language it will generate the client, including the typed models, validation schemas,
@@ -55,7 +42,7 @@ export async function generate({
5542
exportSchemas = false,
5643
request,
5744
write = true,
58-
}: Options): Promise<void> {
45+
}: GenerationOptions): Promise<void> {
5946
const openApi = isString(input) ? await getOpenApiSpec(input) : input;
6047
const openApiVersion = getOpenApiVersion(openApi);
6148
const templates = registerHandlebarTemplates({

src/types/default.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { HttpClient } from "../HttpClient";
2+
3+
export type GenerationOptions = {
4+
input: string | Record<string, any>;
5+
output: string;
6+
httpClient?: HttpClient;
7+
useOptions?: boolean;
8+
useUnionTypes?: boolean;
9+
exportCore?: boolean;
10+
exportServices?: boolean;
11+
exportModels?: boolean;
12+
exportSchemas?: boolean;
13+
request?: string;
14+
write?: boolean;
15+
};

0 commit comments

Comments
 (0)