Skip to content

Instantly share code, notes, and snippets.

@stefangomez
Created July 1, 2019 04:39
Show Gist options
  • Save stefangomez/7e98dac2ce8e9c95d5216b2277ba4e54 to your computer and use it in GitHub Desktop.
Save stefangomez/7e98dac2ce8e9c95d5216b2277ba4e54 to your computer and use it in GitHub Desktop.

Revisions

  1. stefangomez revised this gist Jul 1, 2019. No changes.
  2. stefangomez created this gist Jul 1, 2019.
    49 changes: 49 additions & 0 deletions appsync-client.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    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;