trb-apollo-link-renew
v0.0.6
Published
Terrible Link Renew from Thero Bot
Downloads
3
Readme
Terrible Link Renew
Here is some pseudo code about what is happening inside
renewLink({
getRenewToken: (String) => String
matchError: (ErrorObject) => Boolean
matchOperation: (GraphQLOperation) => Boolean
fetchJwt: (String) => Promise(String)
storeJwt: (String) => Any
})
if matchError(graphQLError) {
if matchOperation(failedGraphQLOperation) {
var renewToken = getRenewToken (expiredJWT)
var newJWT = fetchJwt (renewToken)
retry (failedGraphQLOperation)(newJWT)
storeJwt (newJWT)
}
}
Usage
// vue-apollo.js
const renewJwt = gql`mutation renewJwt($token: String!) { renewJwt(token: $token) { jwtToken } }`
const { apolloClient, wsClient } = createApolloClient({
...defaultOptions,
...options,
link: ApolloLink.from([
renewLink({
// getRenewToken: oldJwt => oldJwt,
// matchError: error => error.message && error.message.match('jwt expired'),
// matchOperation: operation => operation.operationName !== 'renewJwt',
fetchJwt: token =>
apolloClient
.mutate({
mutation: renewJwt,
variables: { token },
})
.then(({ data }) => data && data.renewJwt && data.renewJwt.jwtToken)
.catch(() => null),
storeJwt: token => localStorage.setItem(AUTH_TOKEN, token),
}),
]),
})
Apollo server
// resolvers/Mutation/renewJwt.js
module.exports = async (_, { token }, { jwt, db, appId }) => {
const { jwtData, jwtError } = await jwt.verify(token, {
ignoreExpiration: true,
})
// * delete issued_at and expiration
const { iat, exp, ...oldData } = jwtData
// ? if iat(issuedAt) > user.modifiedAt
if (oldData && oldData.aud === appId) {
const { jwtToken } = await jwt.sign(oldData)
return { jwtToken }
}
}
# schema.gql
type JwtToken { jwtToken: String }
type Mutation { renewJwt(token: String!): JwtToken }