Skip to content
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

[typescript] add call-time middleware support #20430

Open
wants to merge 10 commits into
base: master
Choose a base branch
from

Conversation

davidgamero
Copy link
Contributor

@davidgamero davidgamero commented Jan 9, 2025

ref #18846

make it easier for callers to supply additional middleware for a single method call, without having to pass a whole new Configuration object. The current implementation only allows passing a full new Configuration, which erases SecurityAuthentication headers among other effects, making it difficult to make small edits to requests like overriding a header.

implemented by changing the _options parameter type from undefined | Configuration to undefined | Configuration | []Middleware to preserve backwards compatibility with all existing signatures.

Array.isArray guards are used to narrow the types.

allowing for patterns where middleware can be added for a single call:

api.putPet(
  { name: "mr pet"},
  WithHeader('Content-Type','application/json-patch+json')
)

//WithHeader implements Middleware[] Interface
function WithHeader(key: string, value: string): Middleware[]{
	return [{
		pre: (c: RequestContext)=> {
			return new Promise<RequestContext>((resolve)=>{
				c.headers[key] = value
				resolve(c)
			}
		)},
		post: (c: ResponseContext)=> {return new Promise<ResponseContext>((resolve)=>{ resolve(c) })},
	}]
}

As the PromiseMiddleware is exported in index.ts as Middleware the internal Middleware interface is exported as ObservableMiddleware to allow adding middleware across both the promise and observable layers of the generated client.

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • Run the following to build the project and update samples:
    ./mvnw clean package || exit
    ./bin/generate-samples.sh ./bin/configs/*.yaml || exit
    ./bin/utils/export_docs_generators.sh || exit
    
    (For Windows users, please run the script in Git BASH)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • File the PR against the correct branch: master (upcoming 7.x.0 minor release - breaking changes with fallbacks), 8.0.x (breaking changes without fallbacks)
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

@TiFu (2017/07) @taxpon (2017/07) @sebastianhaas (2017/07) @kenisteward (2017/07) @Vrolijkx (2017/09) @macjohnny (2018/01) @topce (2018/10) @akehir (2019/07) @petejohansonxo (2019/11) @amakhrov (2020/02) @davidgamero (2022/03) @mkusaka (2022/04) @joscha (2024/10)

@davidgamero davidgamero changed the title [typescript] add call-time middleware [typescript] add call-time optional middleware array Jan 9, 2025
@davidgamero davidgamero changed the title [typescript] add call-time optional middleware array [typescript] add call-time middleware support Jan 10, 2025
@@ -42,8 +45,11 @@ export class {{classname}}RequestFactory extends BaseAPIRequestFactory {
* @param {{paramName}} {{description}}
{{/allParams}}
*/
public async {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}_options?: Configuration): Promise<RequestContext> {
let _config = _options || this.configuration;
public async {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}_options?: Configuration{{^useInversify}} | Middleware[]{{/useInversify}}): Promise<RequestContext> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could it also be a separate parameter instead of turning _options into a type union? same for all similar changes in the other files

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, we're okay with users having to pass null/undefined to skip args? I can just put it after _options arg

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we could also just destructure

args?: {middleware?: Middleware[]}

so when adding even more params in the future, we would be able to pass the ones we want by name

Copy link
Contributor Author

@davidgamero davidgamero Jan 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That looks cleaner imo, and easier to consume.
Should the current configuration go in there too?

args?: {
  middleware?: Middleware[],
  configuration?: Configuration
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that wouldn't be backwards compatible, so i would avoid it

if (Array.isArray(_options)){
// call-time middleware provided
calltimeMiddleware = _options
}else{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
}else{
} else {

let observableOptions: Configuration | undefined | Middleware[]
if (Array.isArray(_options)){
observableOptions = _options.map(m => new PromiseMiddlewareWrapper(m))
}else{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
}else{
} else {

@amakhrov
Copy link
Contributor

amakhrov commented Jan 21, 2025

The linked issue mentions providing headers as an option (a property of _options). It would be a much simpler way to achieve the task, IMO.
What are other uses cases that would require passing a full-featured middleware instead?

@davidgamero
Copy link
Contributor Author

davidgamero commented Jan 21, 2025

I dont have a concrete example that requires more than headers.

My initial goal was to be consistent with the existing codebase's patterns which were mostly built around chaining middleware.

Happy to switch to header-only and revisit if it's insufficient later

More like:

args?: {
  headers?: [key: string]: string,
  configuration ?: Configuration
}

@amakhrov
Copy link
Contributor

Using middleware for this is ambiguous because Configuration.middleware is an array.

So if we provide a new array with just a single header-appending middleware, does it mean we want to append it to the existing ones? prepend? or replace?

@davidgamero
Copy link
Contributor Author

Agreed it is't immediately clear where the middleware would go.

Since additional middleware is most specific (as opposed to replacing a whole configuration), i lean towards running it last on request and first on response so it can override the existing RequestContext as needed.

As headers can also be manipulated in middleware, for the header-only approach i expect it would be executed last as an override too. The specified headers would replace existing keys if they exist.

Potentially clearer to call the arg headerOverrides

@amakhrov
Copy link
Contributor

amakhrov commented Jan 21, 2025

Btw, if we go with the middleware approach -isn't it already possible to to what we need by providing middleware in the _options arg?
maybe what's missing is the code to merge _options with the standard configuration in this.configuration (as currently _options will completely replace the latter)?

@davidgamero
Copy link
Contributor Author

Yes that's a possibility, we could allow something like a json merge patch.

The merge would have to allow appending middleware at the end since the order of execution would matter for those.
The rest of the fields are relatively static so merging non-empty fields could work if the types are optional.

At that point potentially just having a middleware merge strategy option could cover the full use case. The other fields would only replace if they are non-empty.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants