Skip to content
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

Feature: Auto refresh token. #21

Open
patrick-motard opened this issue Jan 18, 2021 · 0 comments
Open

Feature: Auto refresh token. #21

patrick-motard opened this issue Jan 18, 2021 · 0 comments

Comments

@patrick-motard
Copy link
Contributor

patrick-motard commented Jan 18, 2021

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant