Last active
December 16, 2018 23:13
-
-
Save r3-yamauchi/80606ca4523d085743fd8e1d8aca4b63 to your computer and use it in GitHub Desktop.
AWS Lambda から AppSync の API を ぶん殴る https://blog.r3it.com/aws-lambda-to-appsync-1aa0c2f1da04
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
require('isomorphic-fetch'); | |
const AUTH_TYPE = require('aws-appsync/lib/link/auth-link').AUTH_TYPE; | |
const AWSAppSyncClient = require('aws-appsync').default; | |
const AmazonCognitoIdentity = require('amazon-cognito-identity-js'); | |
const gql = require('graphql-tag'); | |
const listMessages = gql(` | |
query getConversationMessages($conversationId: ID!, $after: String, $first: Int) { | |
allMessageConnection(conversationId: $conversationId, after: $after, first: $first) { | |
__typename | |
nextToken, | |
messages { | |
__typename | |
id | |
conversationId | |
content | |
createdAt | |
sender | |
isSent | |
} | |
} | |
}`); | |
exports.handler = async (event) => { | |
const poolData = { | |
UserPoolId: process.env['USERPOOL_ID'], | |
ClientId: process.env['CLIENT_ID'] | |
}; | |
const userData = { | |
Username: process.env['USERNAME'], | |
Pool: new AmazonCognitoIdentity.CognitoUserPool(poolData) | |
}; | |
const cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData); | |
const authenticationData = { | |
Username: userData.Username, | |
Password: process.env['PASSWORD'] | |
}; | |
const authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData); | |
const authenticateUser = new Promise((resolve, reject) => { | |
cognitoUser.authenticateUser(authenticationDetails, { | |
onSuccess: (result) => { | |
const idToken = result.getIdToken().getJwtToken(); | |
resolve(idToken); | |
}, | |
onFailure: (err) => { | |
reject(err); | |
}, | |
newPasswordRequired: (userAttributes, requiredAttributes) => { | |
const err = new Error("newPasswordRequired"); | |
reject(err); | |
} | |
}); | |
}); | |
return authenticateUser.then(async (idToken) => { | |
const client = new AWSAppSyncClient({ | |
url: process.env['URL'], | |
region: process.env['REGION'], | |
auth: { | |
type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS, | |
jwtToken: idToken | |
}, | |
disableOffline: true | |
}); | |
const param = { | |
conversationId: "hello", | |
after: null, | |
first: 20 | |
}; | |
const result = await client.query({ | |
query: listMessages, | |
variables: param, | |
fetchPolicy: 'network-only' | |
}); | |
console.log(JSON.stringify(result)); | |
return result; | |
}).catch((err) => { | |
console.log(JSON.stringify(err)); | |
return err; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment