Created
April 26, 2022 13:48
-
-
Save josefaidt/88592d713c0b4c981e8c993188a69c90 to your computer and use it in GitHub Desktop.
Sample AppSync IAM call from Node.js Lambda using AWS SDK v3
This file contains hidden or 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
import crypto from '@aws-crypto/sha256-js' | |
import { defaultProvider } from '@aws-sdk/credential-provider-node' | |
import { SignatureV4 } from '@aws-sdk/signature-v4' | |
import { HttpRequest } from '@aws-sdk/protocol-http' | |
import { default as fetch, Request } from 'node-fetch' | |
const { Sha256 } = crypto | |
const AWS_REGION = process.env.AWS_REGION || 'us-east-1' | |
const QUERY_LIST_USERS = /* GraphQL */ ` | |
query LIST_USERS { | |
listUsers { | |
items { | |
id | |
} | |
} | |
} | |
` | |
/** | |
* @type {import('@types/aws-lambda').APIGatewayProxyHandler} | |
*/ | |
export const handler = async (event) => { | |
console.log(`EVENT: ${JSON.stringify(event)}`) | |
const endpoint = new URL(process.env.API_9966_GRAPHQLAPIENDPOINTOUTPUT) | |
const signer = new SignatureV4({ | |
credentials: defaultProvider(), | |
region: AWS_REGION, | |
service: 'appsync', | |
sha256: Sha256, | |
}) | |
const requestToBeSigned = new HttpRequest({ | |
method: 'POST', | |
headers: { | |
host: endpoint.host, | |
}, | |
hostname: endpoint.host, | |
body: JSON.stringify({ query: QUERY_LIST_USERS }), | |
path: endpoint.pathname, | |
}) | |
const signed = await signer.sign(requestToBeSigned) | |
const request = new Request(endpoint, signed) | |
let statusCode = 200 | |
let body | |
let response | |
try { | |
response = await fetch(request) | |
body = await response.json() | |
if (body.errors) statusCode = 400 | |
} catch (error) { | |
console.log(error) | |
statusCode = 500 | |
body = { | |
errors: [ | |
{ | |
message: error.message, | |
}, | |
], | |
} | |
} | |
return { | |
statusCode, | |
body: JSON.stringify(body), | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment