Skip to content

Instantly share code, notes, and snippets.

@carlosvega20
Created September 27, 2023 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlosvega20/e06f652e2852abaee1e6c42797d12476 to your computer and use it in GitHub Desktop.
Save carlosvega20/e06f652e2852abaee1e6c42797d12476 to your computer and use it in GitHub Desktop.
import * as cdk from 'aws-cdk-lib';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import * as apigateway from 'aws-cdk-lib/aws-apigateway';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as appsync from 'aws-cdk-lib/aws-appsync';
import * as iam from 'aws-cdk-lib/aws-iam';
const { Stack, App, RemovalPolicy } = cdk;
class GraphQLAPIStack extends Stack {
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// DynamoDB Table
const table = new dynamodb.Table(this, 'ItemsTable', {
partitionKey: { name: 'itemId', type: dynamodb.AttributeType.STRING },
removalPolicy: RemovalPolicy.DESTROY, // For demo purposes; use retention policy in production
});
// Lambda Function
const lambdaFunction = new lambda.Function(this, 'GraphQLLambda', {
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'graphql.handler',
code: lambda.Code.fromAsset('lambda'), // Path to your Lambda code
environment: {
DYNAMODB_TABLE_NAME: table.tableName,
},
});
// Grant Lambda permissions to access DynamoDB
table.grantReadWriteData(lambdaFunction);
// API Gateway
const api = new apigateway.RestApi(this, 'GraphQLAPI');
// Lambda Integration
const lambdaIntegration = new apigateway.LambdaIntegration(lambdaFunction, {
proxy: true,
});
// API Gateway Endpoint
const apiResource = api.root.addResource('graphql');
apiResource.addMethod('POST', lambdaIntegration);
// Output the API URL
new cdk.CfnOutput(this, 'GraphQLAPIEndpoint', {
value: api.url,
});
}
}
const app = new App();
new GraphQLAPIStack(app, 'GraphQLAPIStack');
app.synth();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment