Created
January 9, 2022 16:05
-
-
Save ThomasRooney/224fff278c25e652adb4e6776270dd60 to your computer and use it in GitHub Desktop.
appsync invoke
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
import * as https from 'https'; | |
import { URL } from 'url'; | |
const AWS = require('aws-sdk'); | |
export function assertEnv(key: string): string { | |
if (process.env[key] !== undefined) { | |
return process.env[key]!; | |
} | |
throw new Error(`expected environment variable ${key}`); | |
} | |
const aws_appsync_graphqlEndpointP = assertEnv('aws_appsync_graphqlEndpoint'); | |
const aws_appsync_regionP = assertEnv('aws_appsync_region'); | |
const invoke = async (body): Promise<any> => { | |
const [aws_appsync_graphqlEndpoint, aws_appsync_region] = await Promise.all([ | |
aws_appsync_graphqlEndpointP, | |
aws_appsync_regionP, | |
]); | |
const req = new AWS.HttpRequest(aws_appsync_graphqlEndpoint, aws_appsync_region); | |
const endpoint = new URL(aws_appsync_graphqlEndpoint).hostname.toString(); | |
req.method = 'POST'; | |
req.path = '/graphql'; | |
req.headers.host = endpoint; | |
req.headers['Content-Type'] = 'application/json'; | |
req.body = JSON.stringify(body); | |
const signer = new AWS.Signers.V4(req, 'appsync', true); | |
signer.addAuthorization(AWS.config.credentials, AWS.util.date.getDate()); | |
return new Promise((resolve, reject) => { | |
const httpRequest = https.request({ ...req, host: endpoint }, (result) => { | |
let data = ''; | |
result.on('data', (chunk) => { | |
data += chunk; | |
}); | |
result.on('error', (e) => { | |
reject(e); | |
}); | |
result.on('end', () => { | |
try { | |
if (typeof result.statusCode === 'number' && (result.statusCode < 200 || result.statusCode >= 400)) { | |
throw new Error(`unexpected response code ${result.statusCode}: ${data.toString()}`); | |
} | |
const respBody = JSON.parse(data.toString()); | |
resolve(respBody); | |
} catch (e) { | |
reject(e); | |
} | |
}); | |
}); | |
httpRequest.write(req.body); | |
httpRequest.end(); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment