Skip to content

Conversation

@superr-fluous
Copy link

Hi! This is a proof of concept PR for a beforeReturn hook (discussed in #696) that is less strict about return type than afterResponse .
Important note: this PR at least needs some work to be done in terms of types, although basic usage is fully covered.

Why ❔ :

  • more flexible approach than current implementation of afterResponse
  • no overhead associated with JSON de-, serialization when using beforeReturn opposed to afterResponse

Key usage points 🔑 :

  • if specified, the return of last beforeReturn callback is what gets returned by ky
  • beforeReturn is called at the end of hook life-cycle
  • beforeReturn is not called if request is erroneous and throwHttpErrors is not off
  • beforeReturn allows any return from callback
  • in case of a sequence of beforeReturn callbacks ({ beforeReturn: [cb1, cb2, ... ] }) each subsequent callback is invoked with the result of the previous callback invocation

Potential workflow ➡️ :
As I see it, afterResponse can be used to perform additional network operations based on a response (combine multiple requests together, simply send additional requests, or even some exotic retry logic that needs some customized behavior); whereas beforeReturn can be used to ensure consistency of the returned value. Basically, afterResponse is for anything that actually alters the Response, beforeReturn is to derive data from Response

Key developing points 🖊️ :

  • most changes are within TypeScript domain, actual JavaScript is small
  • in order to flexibly type the return value , in case of using beforeReturn, it is required to infer return type from last beforeReturn cb
  • extend and the options argument for ky methods require to consider type collisions among them and beforeReturn exit value

Misc:
While TypeScript-related code is kind of unattractive, it is still the required minimum to derive return type from Options, in a sense that anything else in Options that affects the returned value would need the same approach to reflect it through types

PR progress state 🚧 :
Waiting for comments whether the idea is welcomed

Thanks for taking time to review my PR!!

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.

1 participant