Tokens
This service contains helpers for requesting user auth tokens.
Get an Auth Token
The auth token can be retrieved via the getToken function:
import { quest } from '@rhythm/quest'
import { Socket } from 'phoenix'
import { getToken } from '@rhapsody/tokens'
export const createWebsocket = async () => {
const { token } = await getToken()
const websocket = await new Socket('wss://...', {
params: { token },
})
websocket.connect()
return websocket
}
export const makeRequest = async () => {
const { getHeaders } = await getToken()
return quest.get('...', { headers: getHeaders() })
}
Under the hood, the getToken function is doing quite a few things. First, it keeps a cached version of the token for a preset randomized amount of time (5-9 minutes). Second, if the cached version is not present or is expired, it makes a request to Melody to get a new token. Third, it deduplicates any calls to itself so we only ever make one network request at a time.
Testing
When running unit tests, the cacheToken function can be used to hydrate the cache with a predefined token.
import jwt from 'jsonwebtoken'
import { cacheToken } from '@rhapsody/tokens'
export const JWT = jwt.sign({}, 'secret')
cacheToken(JWT)