openapi-ts icon indicating copy to clipboard operation
openapi-ts copied to clipboard

feat(services): add ability to provide ApiRequestOptions in operation methods

Open kerwanp opened this issue 10 months ago • 3 comments

Related issues

  • #342

Why ?

I have to work with badly written Openapi specifications that does not contain all the available properties available. So when generating the client, the unreferenced properties are not available in the generated types.

As their is a destructuration done in the operation functions it is not possible to pass non typed parameters.

// preview property is not referenced in openapi specifications
getMentors({ filters: [], sort: [], preview: false });
                                      /\ Custom search params not referenced in specifications
// Generated file
	public getMentors(data: $OpenApiTs['/mentors']['get']['req'] = {}): CancelablePromise<$OpenApiTs['/mentors']['get']['res'][200]> {
		const {
                    sort,
                    filters,
                    locale   // <- preview is not extracted from data
                } = data;

		return this.httpRequest.request({
			method: 'GET',
			url: '/mentors',
			query: {
				sort, filters, locale <- data is not passed 
			},
			errors: {
				400: `Bad Request`,
				401: `Unauthorized`,
				403: `Forbidden`,
				404: `Not Found`,
				500: `Internal Server Error`,
			},
		});

What has been done?

The goal of this PR is to provide the ability to override the ApiRequestOptions by adding a new Partial<ApiRequestOptions> in services methods arguments.

    public static postServiceWithEmptyTag(
        data: $OpenApiTs['/api/v{api-version}/no-tag']['post']['req'],
        options: Partial<ApiRequestOptions> = {}
    ): CancelablePromise<$OpenApiTs['/api/v{api-version}/no-tag']['post']['res'][200]> {}

As we do not want to override but merge, I've added a mergeDeep function. (currently located in core/request.ts but could be in a core/utils.ts).

Then we merge the objects together before passing them to the request function.

    public static postServiceWithEmptyTag(
        data: $OpenApiTs['/api/v{api-version}/no-tag']['post']['req'],
        options: Partial<ApiRequestOptions> = {}
    ): CancelablePromise<$OpenApiTs['/api/v{api-version}/no-tag']['post']['res'][200]> {
        const { requestBody } = data;
        return __request(
            OpenAPI,
            mergeDeep(
                {
                    method: 'POST',
                    url: '/api/v{api-version}/no-tag',
                    body: requestBody,
                    mediaType: 'application/json',
                },
                options
            )
        );
    }
}

kerwanp avatar Apr 13 '24 22:04 kerwanp