Skip to content

Indexes on fetch-client interceptors to allow dynamic interceptor management. #2018

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

Open
henry-encord opened this issue May 6, 2025 · 0 comments
Labels
feature 🚀 New feature or request

Comments

@henry-encord
Copy link
Contributor

Description

Currently ejecting interceptors is complicated when they are not defined statically, and managing them dynamically gets messy. I'd like to request using similar logic to axios in adding and removing interceptors.

E.g. we need this functionality because we need to have an interceptor that changes depending on state that is stored in context. So when the state within the context changes, we need to update the interceptor. Accessing an interceptor doesn't really work with the current client in this case.

I've put some suggested changes below to the interceptors class. The purpose of these changes is to expose the index of each interceptor to allow easier removal and also add the ability to update an interceptor based on the index.

class Interceptors<Interceptor> {
  _fns: (Interceptor | null)[];

  constructor() {
    this._fns = [];
  }

  clear() {
    this._fns = [];
  }

  exists(fn: Interceptor | number) {
    if (typeof fn === 'number') {
      return this._fns[fn] !== null;
    } else {
      return this._fns.indexOf(fn) !== -1;
    }
  }

  eject(fn: number | Interceptor) {
    let index = -1
    if (typeof fn === 'number') {
      index = fn;
    } else {
      index = this._fns.indexOf(fn);
    }
    if (index !== -1) {
      this._fns[index] = null;
    }
  }

  update(index: number, fn: Interceptor) {
    if (this._fns[index]) {
      this._fns[index] = fn
      return index
    } else {
      return false
    }
  }

  use(fn: Interceptor) {
    this._fns = [...this._fns, fn];
    return this._fns.length - 1;
  }
}
@henry-encord henry-encord added the feature 🚀 New feature or request label May 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature 🚀 New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant