unjs / ofetch

😱 A better fetch API. Works on node, browser and workers.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Custom hook support

k2so-dev opened this issue · comments

Describe the feature

It would be great to have a feature like custom hooks. At the moment, ofetch has interceptors and this is very convenient, but sometimes it feels like the functionality of $fetch is limited - this concerns the end use of $fetch.
For example, if we specify interceptors in the ofetch.create method - then in the final use case we can only override the interceptors. And just for such cases, when we need to make interceptors as shared, we can call hooks inside the interceptors.

For example, in the options we add hooks:

hooks?: {
  [key: string]: { (context: any): Promise<void> | void };
};

Inside the interceptor we call the hook:

onResponseError: async ({ response, options }) => {
  if (response.statusCode === 422) {
    await options.hooks?.validationErrors(response._data?.errors || [])
  }
}

Example of final $fetch call:

const { data, error } = await useFetch("login", {
  method: "POST",
  body: { emal: "test@test.com", password: "test1234" },
  hooks: {
    validationErrors: (errors) => form.value.setErrors(errors)
  }
});

Do you think this makes sense?

Additional information

  • Would you be willing to help implement this feature?