Skip to content

commit to illustrate changes for custom-http-client (do not merge) #407

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ $ openapi --help
-V, --version output the version number
-i, --input <value> OpenAPI specification, can be a path, url or string content (required)
-o, --output <value> Output directory (required)
-c, --client <value> HTTP client to generate [fetch, xhr, node] (default: "fetch")
-c, --client <value> HTTP client to generate [fetch, xhr, node, custom] (default: "fetch")
--useOptions Use options instead of arguments
--useUnionTypes Use union types instead of enums
--exportCore <value> Write core files to disk (default: true)
Expand Down Expand Up @@ -441,6 +441,14 @@ npm install node-fetch --save-dev
npm install form-data --save-dev
```

### Support for a custom http-client

If you have more sophisticated requirements that are not provided by the generated http-clients, you can specify
`--client custom` and provide your own request-function.

`openapi --input ./spec.json --output ./dist --client custom`


[npm-url]: https://npmjs.org/package/openapi-typescript-codegen
[npm-image]: https://img.shields.io/npm/v/openapi-typescript-codegen.svg
[license-url]: LICENSE
Expand Down
2 changes: 1 addition & 1 deletion bin/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ program
.version(pkg.version)
.requiredOption('-i, --input <value>', 'OpenAPI specification, can be a path, url or string content (required)')
.requiredOption('-o, --output <value>', 'Output directory (required)')
.option('-c, --client <value>', 'HTTP client to generate [fetch, xhr, node]', 'fetch')
.option('-c, --client <value>', 'HTTP client to generate [fetch, xhr, node, custom]', 'fetch')
.option('--useOptions', 'Use options instead of arguments')
.option('--useUnionTypes', 'Use union types instead of enums')
.option('--exportCore <value>', 'Write core files to disk', true)
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export enum HttpClient {
FETCH = 'fetch',
XHR = 'xhr',
NODE = 'node',
CUSTOM = 'custom'
}

export interface Options {
Expand Down
28 changes: 28 additions & 0 deletions src/templates/core/custom/request.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{{>header}}
import { ApiError } from './ApiError';
import type { ApiRequestOptions } from './ApiRequestOptions';
import type { ApiResult } from './ApiResult';

{{>functions/catchErrors}}

export type ExecuteRequest = (options: ApiRequestOptions) => Promise<ApiResult>;

type CustomHttpClient = {
executeRequest?: ExecuteRequest;
};
export const CustomHttpClient: CustomHttpClient = {};

/**
* Request using fetch client
* @param options The request options from the the service
* @result ApiResult
* @throws ApiError
*/
export async function request(options: ApiRequestOptions): Promise<ApiResult> {
if (CustomHttpClient.executeRequest == null) {
throw new Error("No custom request-function has been registered. Use `CustomRequest.requestFunction = async (options) => {...} to implement one.")
}
const result = await CustomHttpClient.executeRequest(options);
catchErrors(options, result);
return result;
}
1 change: 1 addition & 0 deletions src/templates/core/request.hbs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{{#equals @root.httpClient 'fetch'}}{{>fetch/request}}{{/equals}}
{{#equals @root.httpClient 'xhr'}}{{>xhr/request}}{{/equals}}
{{#equals @root.httpClient 'node'}}{{>node/request}}{{/equals}}
{{~#equals @root.httpClient 'custom'}}{{>custom/request}}{{/equals~}}
4 changes: 4 additions & 0 deletions src/utils/registerHandlebarTemplates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import xhrGetResponseBody from '../templates/core/xhr/getResponseBody.hbs';
import xhrGetResponseHeader from '../templates/core/xhr/getResponseHeader.hbs';
import xhrRequest from '../templates/core/xhr/request.hbs';
import xhrSendRequest from '../templates/core/xhr/sendRequest.hbs';
import customRequest from '../templates/core/custom/request.hbs';
import templateExportModel from '../templates/exportModel.hbs';
import templateExportSchema from '../templates/exportSchema.hbs';
import templateExportService from '../templates/exportService.hbs';
Expand Down Expand Up @@ -165,5 +166,8 @@ export function registerHandlebarTemplates(): Templates {
Handlebars.registerPartial('node/sendRequest', Handlebars.template(nodeSendRequest));
Handlebars.registerPartial('node/request', Handlebars.template(nodeRequest));

// Specific files for the custom client implementation
Handlebars.registerPartial('custom/request', Handlebars.template(customRequest));

return templates;
}
29 changes: 29 additions & 0 deletions test/e2e/scripts/custom-client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@

async function customClient(options) {
const url = `${OpenAPI.BASE}${options.path}`;
const token = typeof OpenAPI.TOKEN === 'function' ? await OpenAPI.TOKEN() : OpenAPI.TOKEN;

const headers = options.headers || {};
if (token != null && token !== '') {
headers.authorization = 'Bearer ' + token;
}
console.log("OPTIONS", options, OpenAPI, headers)
return {
ok: true,
status: 200,
body: {
method: options.method,
protocol: 'http',
hostname: 'localhost',
path: options.path,
url: url,
query: options.query,
body: options.body,
headers: headers,
},
statusText: 'OK',
url: url
}
}

module.exports = {customClient}
37 changes: 37 additions & 0 deletions test/e2e/v2.custom.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
'use strict';

const generate = require('./scripts/generate');
const compileWithTypescript = require('./scripts/compileWithTypescript');
const {customClient} = require("./scripts/custom-client");

describe('v2.custom', () => {

beforeAll(async () => {
await generate('v2/custom', 'v2', 'node');
compileWithTypescript('v2/custom');
const {CustomHttpClient} = require('./generated/v3/custom/core/request')
CustomHttpClient.executeRequest = customClient;
}, 30000);

it('requests token', async () => {
const { OpenAPI, SimpleService } = require('./generated/v2/node/index.js');
const tokenRequest = jest.fn().mockResolvedValue('MY_TOKEN')
OpenAPI.TOKEN = tokenRequest;
const result = await SimpleService.getCallWithoutParametersAndResponse();
expect(tokenRequest.mock.calls.length).toBe(1);
expect(result.headers.authorization).toBe('Bearer MY_TOKEN');
});

it('complexService', async () => {
const { ComplexService } = require('./generated/v2/node/index.js');
const result = await ComplexService.complexTypes({
first: {
second: {
third: 'Hello World!'
}
}
});
expect(result).toBeDefined();
});

});
41 changes: 41 additions & 0 deletions test/e2e/v3.custom.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'use strict';

const generate = require('./scripts/generate');
const compileWithTypescript = require('./scripts/compileWithTypescript');
const {customClient} = require("./scripts/custom-client");

describe('v3.custom', () => {

beforeAll(async () => {
await generate('v3/custom', 'v3', 'custom');
compileWithTypescript('v3/custom');
const {CustomHttpClient} = require('./generated/v3/custom/core/request')
CustomHttpClient.executeRequest = customClient;
},30000);

it('requests token', async () => {

const { OpenAPI, SimpleService } = require('./generated/v3/custom/index.js');
const tokenRequest = jest.fn().mockResolvedValue('MY_TOKEN')
OpenAPI.TOKEN = tokenRequest;

const result = await SimpleService.getCallWithoutParametersAndResponse();
expect(tokenRequest.mock.calls.length).toBe(1);
expect(result.headers.authorization).toBe('Bearer MY_TOKEN');
});

it('complexService', async () => {
const { ComplexService } = require('./generated/v3/custom/index.js');
const result = await ComplexService.complexTypes({
first: {
second: {
third: 'Hello World!'
}
}
});
expect(result).toBeDefined();
});

});