awslabs / aws-mobile-appsync-sdk-js

JavaScript library files for Offline, Sync, Sigv4. includes support for React Native
Apache License 2.0
921 stars 266 forks source link

Catch-22 condition with Cognito auth and setting up Vue Apollo #42

Closed ffxsam closed 6 years ago

ffxsam commented 6 years ago

I'm stuck on something in my Vue app.

In src/main.js, I have this:

const client = new AWSAppSyncClient(
  {
    url: process.env.APPSYNC_API_URL,
    region: 'us-east-1',
    auth: {
      type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS,
      jwtToken: async () => await // ??? store.state.user.tokens.IdToken,
    },
  },
  {
    defaultOptions: {
      watchQuery: {
        fetchPolicy: 'cache-and-network',
      },
    },
  }
);

The catch here is that the user has to be authenticated via Cognito before I can supply the ID token, but AppSync needs to be set up immediately so the client object can be used in VueApollo and finally included in the Vue app bootstrap:

const apolloProvider = new VueApollo({
  defaultClient: client,
  defaultOptions: {
    $loadingKey: 'loadingCount',
  },
});

new Vue({
  el: '#app',
  apolloProvider,
  i18n,
  router,
  store,
  components: { App },
  template: '<App/>',
});

I can't figure out how to organize this so that once the user is authenticated via Cognito and their tokens are stored in Vuex state, only then can AppSync connect.

ffxsam commented 6 years ago

Welp, it might help if I used the right path to my user state! This code is correct, and gets the job done:

const client = new AWSAppSyncClient(
  {
    url: process.env.APPSYNC_API_URL,
    region: 'us-east-1',
    auth: {
      type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS,
      jwtToken: async () => store.state.auth.user.tokens.IdToken,
    },
  },
  {
    defaultOptions: {
      watchQuery: {
        fetchPolicy: 'cache-and-network',
      },
    },
  }
);

Leaving this issue here in case it helps someone else. 😁