awslabs / aws-mobile-appsync-sdk-js

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

Vanilla AWS SDK v3 + Apollo V3 query guide #757

Open slikk66 opened 8 months ago

slikk66 commented 8 months ago

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');