Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vanilla AWS SDK v3 + Apollo V3 query guide #757

Open
slikk66 opened this issue Oct 19, 2023 · 0 comments
Open

Vanilla AWS SDK v3 + Apollo V3 query guide #757

slikk66 opened this issue Oct 19, 2023 · 0 comments

Comments

@slikk66
Copy link

slikk66 commented Oct 19, 2023

Since this upgrade thing has been confusing for me, here's a working setup I used to query data from my IAM protected AppSync API in a Typescript Lambda to simply pull some data. Hope it helps someone. Most docs seem to be Amplify and React based. In my case I'm just trying to use CRON-style lambda tasks to pull data and make adjustments to records via my AppSync API.

Packages:
"aws-appsync-auth-link": "^3.0.7",
"aws-appsync-subscription-link": "^3.1.2",
"graphql": "^16.8.1",
"@aws-sdk/credential-providers": "^3.431.0",
"cross-fetch": "^4.0.0",

import fetch from "cross-fetch";
import { createAuthLink } from "aws-appsync-auth-link";
import { gql, ApolloClient, InMemoryCache, HttpLink, ApolloLink } from "@apollo/client/core"; // important bit here to pull from different "core" path if not using REACT

import { fromEnv } from "@aws-sdk/credential-providers";

import { AUTH_TYPE, AuthOptions } from "aws-appsync-auth-link/lib/index";

const region = process.env.AWS_REGION!; /// from Lambda
const url = process.env.GRAPHQL_ENDPOINT!; /// passed in to function configuration 

/// other auth options here (metadata, cognito, provider chain etc: https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-credential-providers/#fromNodeProviderChain
const auth: AuthOptions = {
    type: AUTH_TYPE.AWS_IAM,
    credentials: fromEnv(),
};

const httpLink = new HttpLink({ uri: url, fetch }); // weird that value is URI here, but URL for links below

const link = ApolloLink.from([
    createAuthLink({ url, region, auth }),
    httpLink,
]);

const $client = new ApolloClient({
    link,
    cache: new InMemoryCache(),
});

const getThing = async (id: string) => {
    const GET_THING = gql`
        query GetThing($id: ID!) {
            getThing(id: $id) {
                id
                name
            }
        }
    `;

    return $client.query({
        query: GET_THING,
        variables: { id: id },
    });
};

// -----------

// call as needed in app
let result = await getThing('123');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant