Skip to content

Instantly share code, notes, and snippets.

@dabit3
Last active August 21, 2020 18:28
Show Gist options
  • Save dabit3/70ef21c0c4871eac405f9501dffe2c31 to your computer and use it in GitHub Desktop.
Save dabit3/70ef21c0c4871eac405f9501dffe2c31 to your computer and use it in GitHub Desktop.
Example AppSync GraphQL API
/* Imports from CDK */
import * as appsync from '@aws-cdk/aws-appsync';
import * as db from '@aws-cdk/aws-dynamodb';
/* Creating the API */
const api = new appsync.GraphQLApi(this, 'Api', {
name: 'my-chat-app', // API name
schemaDefinition: appsync.SchemaDefinition.FILE, // Type of schema
schemaDefinitionFile: './schema.graphql', // location of schema
authorizationConfig: { // authorization config
defaultAuthorization: {
authorizationType: appsync.AuthorizationType.API_KEY
},
}
});
/* Create the DynamoDB table */
const messageTable = new db.Table(this, 'MessageTable', {
partitionKey: {
name: 'id',
type: db.AttributeType.STRING,
},
});
/* Connect the table to the API */
const messageDS = api.addDynamoDbDataSource('messageDataSource', 'Table for Messages"', messageTable);
// Resolver for the Query "getMessages" that scans the DyanmoDb table and returns the messages.
messageDS.createResolver({
typeName: 'Query',
fieldName: 'getMessages',
requestMappingTemplate: MappingTemplate.dynamoDbScanTable(),
responseMappingTemplate: MappingTemplate.dynamoDbResultList(),
});
// Resolver for the Mutation "createMessage" that puts the item into the DynamoDb table.
messageDS.createResolver({
typeName: 'Mutation',
fieldName: 'createMessage',
requestMappingTemplate: MappingTemplate.dynamoDbPutItem(PrimaryKey.partition('id').auto(), Values.projecting('message')),
responseMappingTemplate: MappingTemplate.dynamoDbResultItem(),
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment