Skip to content

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

Open
@henry-encord

Description

@henry-encord

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;
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions