trb-apollo-link-renew

0.0.6 • Public • Published

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 }

Readme

Keywords

none

Package Sidebar

Install

npm i trb-apollo-link-renew

Weekly Downloads

0

Version

0.0.6

License

ISC

Unpacked Size

4.01 kB

Total Files

3

Last publish

Collaborators

  • gcoda