8000 feat: auto retry for arbitrary HTTP status code · Issue #109 · unjs/ofetch · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
feat: auto retry for arbitrary HTTP status code #109
Closed
@Nightfly-student

Description

@Nightfly-student

Hi,

I am trying to auto retry if there was an error. I am using JWT with refresh tokens and want to refresh the token if the server sends an error.

const apiFetch = $fetch.create({
  retry: 1,
  keepalive: true,
  async onRequest({ request, options }) {
    var token = useCookie<tokenObject>("token").value;
    if (token && token.access_token) {
      options.headers = { Authorization: "Bearer " + token.access_token };
    }
  },
  async onResponseError({ request, response, options }) {
    if (response.status === 403) {
      const config = useRuntimeConfig();

      const check = new Promise((resolve, reject) => {
        try {
          apiFetch(`${config.DOMAIN}/api/refresh`, {
            method: "POST",
            body: {
              refreshToken: useCookie<tokenObject>("token").value.refresh_token,
            },
          }).then((res) => {
            const token = res;
            useCookie<tokenObject>("token").value = token;
            option
714C
s.retry = 1;
            resolve(true);
          });
        } catch (err) {
          reject();
        }
      });
      console.log("hi");
      console.log(options);
    }
  },
});

The code to catch the request

    async logout() {
      const config = useRuntimeConfig();
      await apiFetch<dataObject>(`${config.DOMAIN}/api/users/logout`, {
        retry: 3,
        method: "POST",
        body: {
          token: useCookie<tokenObject>("token").value.refresh_token,
        },
      }).then(() => {
        useCookie("user").value = undefined;
        useCookie("token").value = undefined;
        this.user = null;
        this.token = null;
        this.isAuthenticated = false;
        this.isAdmin = false;
        this.isMod = false;
        this.isAffiliate = false;
        const router = useRouter();
        router.push("/");
      });
    },

example of call. both have retry both don't retry.

Let me know :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0