hey-api / openapi-ts

✨ Turn your OpenAPI specification into a beautiful TypeScript client
https://heyapi.vercel.app
Other
1.01k stars 83 forks source link

Define required headers in one place for all service methods #906

Open SpiffyJif opened 1 month ago

SpiffyJif commented 1 month ago

Description

Hi! The OpenAPI spec I'm working with has a required header parameter (SomeHeader) for certain methods. See below:

[/some/endpoint/get:]
operationId: SomeOperation
parameters:
 - name: SomeHeader
   in: header
   required: true

I am using this library to generate types/methods that will be used for an API wrapper SDK. This SDK will consist only of the methods that require the SomeHeader header. Since every single method in this API is going to use SomeHeader, it'd be great if I could define this in just one place, such as in the client config. However, because the header parameter is required in the OpenAPI spec, each generated service method requires the header in its input:

// generated input type for SomeOperation
export type SomeOperationData = {
    headers: {
        'SomeHeader': string;  // this is required
    };
    ...
};

This means that despite setting the header in the client config, each service method still require me to pass in the header. Is there any way I can avoid having to pass in the header for every single method?

// ideally I can just define this here and avoid passing the header in every single method call
client.setConfig({
      ...,
      headers: {
        "SomeHeader": "some-value",
      },
});

This works perfectly if the header is optional, but because it's required in the OpenAPI spec, the generated input type also requires it. I'd really appreciate if I could achieve this without making the header optional in the OpenAPI spec.

mrlubos commented 1 month ago

@SpiffyJif to clarify, the proposed approach you have works, but TypeScript will complain, correct? At which point, this becomes a TypeScript issue rather than a new feature. If that's true, there are two possible approaches – either provide a mechanism to alter the generated types (without modifying your OpenAPI spec) or improve TypeScript interfaces. My general take would be to attempt to do the latter, I am just not sure how doable it is. I can't find that discussion now, but other people requested this too in relation to throwOnError. The underlying problem is the same, the code works, but TypeScript does not know that.

itstueben commented 1 day ago

Looks the same here: https://github.com/hey-api/openapi-ts/issues/1020