Skip to content

Instantly share code, notes, and snippets.

@damianrr
Last active March 6, 2020 22:42
Show Gist options
  • Save damianrr/6cd78290c56b960bb2f4d543423b83a2 to your computer and use it in GitHub Desktop.
Save damianrr/6cd78290c56b960bb2f4d543423b83a2 to your computer and use it in GitHub Desktop.
How to query/mutate AppSync's GraphQL from within Amplify's lambda functions by login into Cognito user pool and reusing Authorization token.
const R = require('ramda');
const aws = require("aws-sdk");
const { GraphQLClient } = require("graphql-request");
aws.config.update({
region: process.env.REGION
});
const cognitoidentityserviceprovider = new aws.CognitoIdentityServiceProvider({
apiVersion: "2016-04-18"
});
const parameterStore = new aws.SSM({ region: process.env.REGION });
const myMutation = `mutation CreateThing($input: CreateThingInput!) {
createThing(input: $input) {
id
}
}`;
exports.handler = async function() {
// ... do my thing and get my data ...
const params = await parameterStore.getParameters({
Names: ["myClientId", "myUsername", "myPassword"],
WithDecryption: true
}).promise()['Parameters'];
const cognitoParams = {
AuthFlow: "ADMIN_NO_SRP_AUTH",
ClientId: R.find(R.propEq('Name', 'myClientId'))(params).Value,
UserPoolId: process.env.AUTH_COGNITOPORTAL_USERPOOLID,
AuthParameters: {
USERNAME: R.find(R.propEq('Name', 'myUsername'))(params).Value,
PASSWORD: R.find(R.propEq('Name', 'myPassword'))(params).Value
}
};
const login = await cognitoidentityserviceprovider
.adminInitiateAuth(cognitoParams)
.promise();
const client = new GraphQLClient(
process.env.API_PORTAL_GRAPHQLAPIENDPOINTOUTPUT,
{
headers: {
Authorization: login.AuthenticationResult.IdToken,
"Content-Type": "application/json"
}
}
);
await client.request(myMutation, {
input: {
id: "something",
items: ["my stuff"]
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment