unjs / unjs/ofetch

onOkResponse interceptor

Open
#348 5 comments 5 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
TypeScript
Stars
5.4k
Forks
195
PR merge metrics
No merged PRs in 30d

Description

Describe the feature

Would anyone think it's helpful to add a new ofetch interceptor? https://github.com/unjs/ofetch#%EF%B8%8F-interceptors

I'm thinking about an onOkResponse interceptor.

Because in my project I have a custom useFetch call that has an onResponseError interceptor as well as an onResponse handler (for successful responses).

Reason is, I must wrap my logic in onResponse handler with if (ctx.response.ok) { ... . In the quest to eliminate boilerplate, I wonder if it would be valuable to add the onOkResponse interceptor, that only runs if ctx.response.ok is true - so the exact opposite of onResponseError which only runs if ctx.response.error is not true.

This idea stemmed from me debugging why my interceptor wouldn't run for a couple hours. The root cause was a silent error in onResponse which blocked onResponseError from running. (Maybe this should be a separate issue).

My onResponse handler depends on the request body to be defined, but during an error response it isn't defined and I got a silent error. Only after wrapping my logic with if (ctx.response.ok) does my onResponseError interceptor run.

Here is a minimal reproduction of the interceptors getting blocked, I think it will work for any other set of interceptors:

const { data } = await useFetch('/api/has-error', {
  onResponse() {
    console.log('On response handler');
    throw new Error('todo');
  },
  onResponseError() {
    // this does not run because error thrown from `onResponse()` interceptor
    console.log('On response error handler');
  },
});

Since an error is thrown from onResponse -- onResponseError will not run.

Additional information
  • Would you be willing to help implement this feature?

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked ofetch interceptor documentation and compare the existing onResponse and onResponseError behavior described in the issue. Check how the useFetch example handles successful and error responses; done means the proposed onOkResponse behavior and the interaction with errors are defined and covered by appropriate tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
api
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.