Last active
August 17, 2022 18:28
-
-
Save undefobj/abb8a42a5c59606fb4126f47a383c48a to your computer and use it in GitHub Desktop.
Calling AppSync from Lambda
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const https = require('https'); | |
const AWS = require("aws-sdk"); | |
const urlParse = require("url").URL; | |
const appsyncUrl = process.env.API_BACKENDGRAPHQL_GRAPHQLAPIENDPOINTOUTPUT; | |
const region = process.env.REGION; | |
const endpoint = new urlParse(appsyncUrl).hostname.toString(); | |
const graphqlQuery = require('./query.js').mutation; | |
const apiKey = process.env.API_KEY; | |
exports.handler = async (event) => { | |
const req = new AWS.HttpRequest(appsyncUrl, region); | |
const item = { | |
input: { | |
title: "Lambda Item", | |
Content: "Item Generated from Lambda" | |
} | |
}; | |
req.method = "POST"; | |
req.headers.host = endpoint; | |
req.headers["Content-Type"] = "application/json"; | |
req.body = JSON.stringify({ | |
query: graphqlQuery, | |
operationName: "createLambdaGraphQL", | |
variables: item | |
}); | |
if (apiKey) { | |
req.headers["x-api-key"] = apiKey; | |
} else { | |
const signer = new AWS.Signers.V4(req, "appsync", true); | |
signer.addAuthorization(AWS.config.credentials, AWS.util.date.getDate()); | |
} | |
const data = await new Promise((resolve, reject) => { | |
const httpRequest = https.request({ ...req, host: endpoint }, (result) => { | |
result.on('data', (data) => { | |
resolve(JSON.parse(data.toString())); | |
}); | |
}); | |
httpRequest.write(req.body); | |
httpRequest.end(); | |
}); | |
return { | |
statusCode: 200, | |
body: data | |
}; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = { | |
mutation: `mutation createLambdaGraphQL($input: CreateLambdaGraphQLInput!) { | |
createLambdaGraphQL(input: $input) { | |
id | |
title | |
Content | |
} | |
} | |
` | |
} |
Just FYI, this was taken from the official AWS Amplify docs here: https://docs.amplify.aws/cli/function#signing-a-request-from-lambda
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks a lot for this gist!