adamgrieger/spotify-web-api-ts

Feature: Auto refresh token.

patrick-motard opened this issue · 0 comments

It would be nice if the client could be responsible for managing refreshing the token (optionally). Here is some code I've written that achieves this externally:

    const client = new SpotifyWebApi(this.config);
    const that = this;
    const handler = {
      // `apply` is a trap for function calls
      apply: (target: any, arg: any, args: any) => {
        return target(args);
        console.log('is this real life');
      },
      // `get` is a trap for object properties. All of the
      // methods/namespaces on the SpotifyClient are objects,
      // so this is the trap that's triggered, even though we
      // are calling functions on the client.
      get: (target: any, prop: any) => {

        if (!that.tokenExpired()) {
          return target[prop];
        }

        const ignoredFunctions = [
          'getRefreshedAccessToken',
          'getAccessToken',
          'http',
          'setAccessToken',
          'clientId',
          'clientSecret',
          'then',
          'constructor'
        ]

        if (ignoredFunctions.indexOf(prop) !== -1) {
          return target[prop];
        }

        return that.refreshAccessToken()
          .then(() => {
            // console.log(`new token: ${that.authToken}`);
            return target[prop];
          });
      },
    };
    const clientProxy = new Proxy(client, handler);
    this.client = clientProxy;

I've excluded some code here, where I initially call getRefreshableAuthorizationUrl, for brevity.
It would be ideal if the client just did a check internally to see if the token needed to be refreshed, and did it for the user. What do you think?