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

Barrier: Add a way to check if it's active asynchronously #457

Open
optislav opened this issue Mar 21, 2024 · 1 comment
Open

Barrier: Add a way to check if it's active asynchronously #457

optislav opened this issue Mar 21, 2024 · 1 comment
Labels
scope:core type:enhancement New feature or request
Milestone

Comments

@optislav
Copy link

In the docs, we have this example:

import { createBarrier } from '@farfetched/core';

const $authToken = createStore(/* ... */);

const authBarrier = createBarrier({
  active: combine($authToken, (token) => isTokenInvalid(token)),
});

However, there is no way to check if the token is valid synchronously in Firebase, as getIdToken() always returns a promise.
https://firebase.google.com/docs/reference/js/v8/firebase.User#getidtoken

Maybe active should also accept an effect that returns a boolean?

@igorkamyshev igorkamyshev added type:enhancement New feature or request scope:core labels Apr 2, 2024
@igorkamyshev igorkamyshev added this to the v1.0 milestone Apr 4, 2024
@optislav
Copy link
Author

optislav commented Apr 5, 2024

We can use an external library (e.g., jwt-decode) to validate the Firebase token.
So even though we can't get the token from the Firebase SDK synchronously, this barrier will get it asynchronously if the token is undefined.

const FIVE_MINUTES_MS = 5 * 60 * 1000 // Firebase default behavior to fetch new token if 5 minutes left
const isTokenAlmostExpired = (jwt: string | null) => {
  if (!jwt) return true
  const { exp } = jwtDecode(jwt)
  if (!exp) return true
  return Date.now() + FIVE_MINUTES_MS > exp * 1000
}

export const authBarrier = createBarrier({
  active: combine($authToken, (token) => isTokenAlmostExpired(token)),
  perform: [getTokenMutation],
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
scope:core type:enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants