Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read data from cache graphql apollo 2.0

I am using apollo 2.0. I first make authUser graphql call to server for given username and password, which generate jwt token and return back token in response. I do see that on successful login, User is stored in cache as id key value. I do have Buy button where I need to make validateSSOSession for given token. For validateSSOSession, I need to read token from cache.

I gone through client.readQuery, client.fragementQuery but both are not applicable for my case bcz client.readQuery expect that same query had been called before to server and I should have same variable. Since I don't have username/password therefore I can't call client.readQuery. Similarly, client.fragementQuery expect id as mandatory. Since I don't have id therefore can't use it.

For time being, I am simply iterating data from cache and filtering for User as below.

const data = client.cache.data.data;
  const users = _.values(data).filter(obj=>(obj.__typename==='User' && obj.token));
  const token = users[0].token;

  // Make graphql call to validate sso
  const { data } = await client.query({
    query: GET_SSO_USER,
    variables: { token }
  });

  const authenticated = data.getSingleSignOnUser.user.userId;

Is there alternate easy way to query User from cache for given condition?

like image 526
joy Avatar asked May 06 '18 07:05

joy


1 Answers

I use client.readQuery(). See the docs about that https://www.apollographql.com/docs/react/api/apollo-client.html#ApolloClient.readQuery

import gql from 'graphql-tag';
import { withApollo } from "react-apollo";

const MY_QUERY = gql`
    query {
      user {email}
    }`;

const MyReactComp = ({client}) =>{
    const someQueryResult = client.readQuery({ query: MY_QUERY });
        return someQueryResult.user ? 'hello user' : 'oops';
    }

export default withApollo(MyReactComp);
like image 170
proti Avatar answered Oct 20 '22 04:10

proti