felangel / fresh

🍋 A token refresh library for Dart.
https://github.com/felangel/fresh
360 stars 57 forks source link

[fresh_graphql] shouldRefresh example needed #81

Closed subzero911 closed 4 months ago

subzero911 commented 1 year ago

Can't figure out how to implement a shouldRefresh condition. shouldRefresh: (response) => response.errors... // somehow check if a token is stale ?

Y-ndm commented 1 year ago
shouldRefresh: (_) {
        print("SHOULD REFRESH TOKEN?");
        if (token == null || token == '') {
          print("SHOULD REFRESH TOKEN? 2");
          return true;
        } else {
          if (JwtDecoder.isExpired(token ?? '')) {
            print("TOKEN IS EXPIRED");
            return true;
          } else {
            print("TOKEN IS NOT EXPIRED");
            return false;
          }
        }
      },
Y-ndm commented 1 year ago
shouldRefresh: (_) {
        print("SHOULD REFRESH TOKEN?");
        if (token == null || token == '') {
          print("SHOULD REFRESH TOKEN? 2");
          return true;
        } else {
          if (JwtDecoder.isExpired(token ?? '')) {
            print("TOKEN IS EXPIRED");
            return true;
          } else {
            print("TOKEN IS NOT EXPIRED");
            return false;
          }
        }
      },

Here is JwtDecoder.

steveroseik commented 6 months ago

Can you provide it in pub.dev example for other people? the example is useful and would definitely benefit others

subzero911 commented 6 months ago

That's how it's implemented in my project. The backend sends the custom error code E_TOKEN_INACTIVE, when it's expired

shouldRefresh: (response) {
      final errors = response.errors;
      return errors != null &&
          errors.isNotEmpty &&
          errors.firstWhereOrNull((e) => e.extensions?['code'] == GraphqlErrorCodes.eTokenInactive) != null;
    },
felangel commented 4 months ago

Closing for now since the way to invalidate a token will likely vary.