How to call AWS AppSync from lambda?

Viewed 571

I am trying to call AWS AppSync service from AWS Lambda function using IAM permissions. Just a basic mutation or query call. I found this tutorial:

https://aws.amazon.com/blogs/mobile/supporting-backend-and-internal-processes-with-aws-appsync-multiple-authorization-types/

but it no longer works with the latest sdks. Errors out on lines 3, 4, etc.

require('isomorphic-fetch');
const AWS = require('aws-sdk/global');
const AUTH_TYPE = require('aws-appsync').AUTH_TYPE;
const AWSAppSyncClient = require('aws-appsync').default;
const gql = require('graphql-tag');
    
const config = {
    url: process.env.APPSYNC_ENDPOINT,
    region: process.env.AWS_REGION,
    auth: {
        type: AUTH_TYPE.AWS_IAM,
        credentials: AWS.config.credentials,
    },
    disableOffline: true
};
    
const createLogMutation =
    `mutation createLog($input: CreateLogInput!) {
        createLog(input: $input) {
            id
            event
            detail
        }
    }`;
    
const client = new AWSAppSyncClient(config);
    
exports.handler = (event, context, callback) => {
    
      // An expected payload has the following format:
      // {
      //   "event": "sample event",
      //   "detail": "sample detail"
      // }
    
    const payload = event['Records'][0]["Sns"]['Message'];
    
    if (!payload['event']) {
        callback(Error("event must be provided in the message body"));
        return;
    }
    
    const logDetails = {
        event: payload['event'],
        detail: payload['detail']
    };
    
    (async () => {
        try {
            const result = await client.mutate({
                mutation: gql(createLogMutation),
                variables: {input: logDetails}
            });
            console.log(result.data);
            callback(null, result.data);
        } catch (e) {
            console.warn('Error sending mutation: ',  e);
            callback(Error(e));
        }
    })();
};

Can someone please post a basic code for calling query/mutation from lambda using IAM permissions?

0 Answers
Related