Skip to content

Instantly share code, notes, and snippets.

@dmost714
Last active September 21, 2022 15:42
Show Gist options
  • Save dmost714/223b0d3b5482fdd6eb75fea7b28b6056 to your computer and use it in GitHub Desktop.
Save dmost714/223b0d3b5482fdd6eb75fea7b28b6056 to your computer and use it in GitHub Desktop.
Example calling GQL from Lambda using AppSync
const getCampaign = /* GraphQL */ `
query GetCampaign($id: ID!) {
getCampaign(id: $id) {
id
status
title
postcardDesignId
landingPage
createdAt
updatedAt
accountCampaignsId
}
}
`
const getCampaignById = async (client, campaignId) => {
const variables = { id: campaignId }
try {
return await executeQuery(client, getCampaign, 'getCampaign', variables)
} catch (error) {
console.log(`executeQuery error`, error)
}
}
require("isomorphic-fetch")
const AWSAppSyncClient = require("aws-appsync").default
const { AUTH_TYPE } = require("aws-appsync")
const gql = require('graphql-tag')
const AWS = require('aws-sdk')
const initializeClient = () => new AWSAppSyncClient({
url: process.env.API_YOURAPPNAME_GRAPHQLAPIENDPOINTOUTPUT,
region: process.env.REGION,
auth: {
type: AUTH_TYPE.AWS_IAM,
credentials: AWS.config.credentials
},
disableOffline: true,
})
const executeQuery = async (client, query, operationName, variables) => {
try {
const response = await client.query({
query: gql(query),
variables,
fetchPolicy: "no-cache",
})
return response.data[operationName]
} catch (err) {
console.log(`ERROR executeQuery ${operationName}`, err)
throw err
}
}
const executeMutation = async (client, mutation, operationName, variables) => {
try {
const response = await client.mutate({
mutation: gql(mutation),
variables,
fetchPolicy: "no-cache",
})
return response.data[operationName]
} catch (err) {
console.log(`ERROR executeMutation ${operationName}`, err)
throw err
}
}
module.exports = {
initializeClient,
executeQuery,
executeMutation
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment