Created
          July 1, 2019 04:39 
        
      - 
      
- 
        Save stefangomez/7e98dac2ce8e9c95d5216b2277ba4e54 to your computer and use it in GitHub Desktop. 
    amplify/appsync client setup for cognito authed users + unauthed users via AWS_IAM
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | import Amplify from "@aws-amplify/core"; | |
| import Auth from "@aws-amplify/auth"; | |
| import { setContext } from "apollo-link-context"; | |
| import { ApolloLink } from "apollo-link"; | |
| import { createHttpLink } from "apollo-link-http"; | |
| import AWSAppSyncClient, { AUTH_TYPE, createAppSyncLink } from "aws-appsync"; | |
| import awsConfig from "../aws-exports"; | |
| Amplify.configure({ | |
| ...awsConfig, | |
| Analytics: { disabled: true } | |
| }); | |
| const appsyncClient = new AWSAppSyncClient(awsConfig, { | |
| link: createAppSyncLink({ | |
| url: awsConfig.aws_appsync_graphqlEndpoint, | |
| region: awsConfig.aws_appsync_region, | |
| auth: { | |
| type: AUTH_TYPE.AWS_IAM, | |
| credentials: async () => await Auth.currentCredentials() | |
| }, | |
| resultsFetcherLink: ApolloLink.from([ | |
| setContext(async (request, previousContext) => { | |
| try { | |
| const session = await Auth.currentSession(); | |
| if (session) { | |
| delete previousContext.headers["X-Amz-Security-Token"]; | |
| return { | |
| headers: { | |
| ...previousContext.headers, | |
| Authorization: session.getIdToken().getJwtToken() | |
| } | |
| }; | |
| } | |
| } catch (e) { | |
| // log or catch error | |
| } | |
| return { | |
| headers: previousContext.headers | |
| }; | |
| }), | |
| createHttpLink({ | |
| uri: awsConfig.aws_appsync_graphqlEndpoint | |
| }) | |
| ]) | |
| }) | |
| }); | |
| export default appsyncClient; | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Thanks for this!
You might need to add
complexObjectsCredentials: async () => await Auth.currentCredentials(),betwen L21-L22 to avoid linting, and/or if you intend to upload to S3 from Amplify.