Skip to content

Commit

Permalink
feat: config file support reading from npm module
Browse files Browse the repository at this point in the history
  • Loading branch information
shijistar committed May 4, 2024
1 parent 38f735c commit 5bc9cda
Show file tree
Hide file tree
Showing 10 changed files with 35 additions and 23 deletions.
15 changes: 11 additions & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
# 1.0.0-alpha.0 (2024-05-02)
# [1.1.0](https://github.com/shijistar/swagger-api-hub/compare/v1.0.0...v1.1.0) (2024-05-04)

### Features

- add commitlint ([fba1adf](https://github.com/shijistar/swagger-api-hub/commit/fba1adfc3d440c7b5b2c24eb2514053ae8d4556b))
- add husky and lint-staged ([d58e331](https://github.com/shijistar/swagger-api-hub/commit/d58e3318e48df67dcbe63df4e9287d810d531bae))
- add main implementation of swagger-api-hub ([63af1d3](https://github.com/shijistar/swagger-api-hub/commit/63af1d3b545d1f403928067130d3db7b077561ad))
- config file support reading from npm module ([a738538](https://github.com/shijistar/swagger-api-hub/commit/a738538c9abc0c26d0cee1d9ba4c63a65e1e87e4))

# 1.0.0 (2024-05-03)

### Features

- add commitlint ([d2fe275](https://github.com/shijistar/swagger-api-hub/commit/d2fe275d8296913a395eefdd53974722aa74af90))
- add husky and lint-staged ([9bc1c7e](https://github.com/shijistar/swagger-api-hub/commit/9bc1c7ef913ee079a7acff05ef6e50abc9b9016c))
- add main implementation of swagger-api-hub ([37c71fc](https://github.com/shijistar/swagger-api-hub/commit/37c71fc1a934ad901c6de7da68bc145e2d12817d))
- change name to swagger-api-hub ([38f735c](https://github.com/shijistar/swagger-api-hub/commit/38f735cf19f903ddb47d331a1d11df2e9fc4e8b2))
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ $ swagger-api-hub
$ swagger-api-hub config/services.ts
```

The configuration file should export an array of `ServiceConfig` objects. If you export only one object, it will generate the code directly without prompting. The config file extension can be `.ts`, `.js`, `.json`, or any other module types supported by Node.js.
The configuration file should export an array of `ServiceConfig` objects. If you export only one object, it will generate the code directly without prompting.

The config file can be either local path or npm module path, and the file extension can be `.ts`, `.js`, `.json`, or any other module types supported by Node.js.

The file should look like this:

Expand Down Expand Up @@ -61,7 +63,7 @@ The `ServiceConfig` object has the following properties:

- `id`: _[required]_ A unique identifier for the service.
- `name`: A human-readable name for the service.
- `url`: _[required]_ The URL of the OpenAPI specification file. If you have a local file, you can use `input` instead of `url` to specify the file path. Or you can even use `spec` to provide the OpenAPI specification object directly. Either `url`, `input`, or `spec` is required.
- `url`: _[required]_ The URL of the OpenAPI specification file. If you have a local file, you can use `input` instead of `url` to specify the file path. Or you can even use `spec` to provide the OpenAPI specification object directly. Either url, input, or spec is required.
- `apiBase`: The base path of all API endpoints. The service may be hosted on a subpath of the main domain, e.g., _/public-api/iam/v3_, then the apiBase is _/public-api_ in this case. If the original api path from the OpenAPI specification is acceptable, you don't need this field.
- `crossOrigin`: Whether to use the absolute api path when calling the service. This is useful when the service is hosted on a different domain and you need to set the `Access-Control-Allow-Origin` header. Default is `false`.
- `output`: The output directory for the generated code. The default is `./src/api/{id}`.
Expand Down
2 changes: 2 additions & 0 deletions cli/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './generate';
export type * from './types';
14 changes: 8 additions & 6 deletions cli/repl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,33 @@ import type { ServiceConfig } from './types';

const program = new commander.Command();

process.title = 'swagger-api-hub-cli';

program
.name(Object.keys(packageJson.bin)[0])
.description('Generate front-end interface code to interact with OpenAPI-based backend services')
.usage('[options] [config-path]')
.argument(
'[config-path]',
'Path to the configuration file, if not specified, the default configuration file will be used',
'Path to the configuration file, if not specified, the default file path will be used',
'./swagger-api-hub.config.ts'
)
.helpOption('-h, --help')
.version(packageJson.version, '-v, --version')
.action(async (configPath) => {
const absPath = resolve(configPath);
let absPath: string;
try {
absPath = require.resolve(configPath);
} catch (error) {
absPath = resolve(configPath);
}
if (!existsSync(absPath)) {
signale.fatal('Config file not found:', configPath);
process.exit(1);
}

let config: ServiceConfig[] | ServiceConfig;
try {
// support both module files and json files
// eslint-disable-next-line @typescript-eslint/no-var-requires
const originalConfig = require(resolve(configPath));
const originalConfig = require(absPath);
config = originalConfig?.default ?? originalConfig;
} catch (error) {
signale.fatal(`Config file parse error (${configPath}):`, error);
Expand Down
7 changes: 5 additions & 2 deletions cli/types.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import type { GenerateApiParams } from 'swagger-typescript-api';

/**
* The configuration of a service.
*/
export type ServiceConfig = GenerateApiParams & {
/** the unique id of service */
/** The unique id of service */
id: string;
/** the friendly name of service */
/** The friendly name of service */
name?: string;
/**
* The base path of all API endpoints.
Expand Down
2 changes: 0 additions & 2 deletions index.ts

This file was deleted.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "swagger-api-hub",
"version": "1.0.0",
"version": "1.1.0",
"description": "Generate front-end access code for swagger backend services in one click",
"keywords": [
"OpenApi",
Expand All @@ -18,7 +18,8 @@
},
"license": "MIT",
"author": "李凤宝 <[email protected]>",
"main": "index.js",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"bin": {
"swagger-api-hub": "./bin/swagger-api-hub.js"
},
Expand Down
2 changes: 0 additions & 2 deletions sample/swagger-api-hub.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,12 @@ const services: ServiceConfig[] = [
id: 'iam',
name: 'User Management Service',
url: 'https://api.example.com/iam/swagger/v3',
output: './src/api/iam',
},
{
id: 'asset',
name: 'Asset Management Service',
url: 'https://api.example.com/asset/swagger/v3',
apiBase: '/asset',
output: './src/api/asset',
},
];
export default services;
4 changes: 1 addition & 3 deletions templates/http-clients/axios-http-client.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,13 @@ export enum ContentType {

export class HttpClient<SecurityDataType = unknown> {
public instance: AxiosInstance;
private axiosConfig: AxiosRequestConfig;
private securityData: SecurityDataType | null = null;
private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"];
private secure?: boolean;
private format?: ResponseType;

constructor(axiosInstance?: AxiosInstance, { securityWorker, secure, format, ...axiosConfig }: ApiConfig<SecurityDataType> = {}) {
this.instance = axiosInstance ?? axios.create(axiosConfig);
this.axiosConfig = axiosConfig;
this.secure = secure;
this.format = format;
this.securityWorker = securityWorker;
Expand All @@ -72,7 +70,7 @@ export class HttpClient<SecurityDataType = unknown> {
...(params1.headers || {}),
...((params2 && params2.headers) || {}),
},
baseURL: params2?.baseURL || params1?.baseURL || this.axiosConfig?.baseURL,
baseURL: params2?.baseURL || params1?.baseURL || this.instance.defaults.baseURL,
};
}

Expand Down
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"jsx": "react-jsx",
"strict": true,
"skipLibCheck": true,
"declaration": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": false,
Expand Down

0 comments on commit 5bc9cda

Please sign in to comment.