18 Jul 2023 |
post
Building a websocket echo server in 33 lines of code
The code below shows how to build a simple websocket echo server with AWS Lambda and API Gateway, with all the infrastructure management handled by Pulumi. A GitHub repository with the full code is available here.
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
const echoHandler = new aws.lambda.CallbackFunction("echoHandler", {
: async (event: any) => ({ statusCode: 200, body: event.body })
callback;
})
const api = new aws.apigatewayv2.Api("api", { protocolType: "WEBSOCKET" });
const integration = new aws.apigatewayv2.Integration("defaultIntegration", {
: api.id,
apiId: "AWS_PROXY",
integrationType: echoHandler.invokeArn,
integrationUri;
})
const defaultRoute = new aws.apigatewayv2.Route("defaultRoute", {
: api.id,
apiId: "$default",
routeKey: pulumi.interpolate`integrations/${integration.id}`,
target;
})
const deployment = new aws.apigatewayv2.Deployment(
"deployment",
: api.id },
{ apiId: [defaultRoute]}
{ dependsOn;
)
const stage = new aws.apigatewayv2.Stage("stage", {
: api.id,
apiId: "dev",
name: deployment.id,
deploymentId;
})
export const url = pulumi.interpolate`${api.apiEndpoint}/${stage.name}`;
echoHandler
defines a Lambda function that returns the body of the request (the echo).api
creates a new API Gateway configured for websockets.integration
associates the Lambda function with the API Gateway. It also configures the integration type to beAWS_PROXY
, which means that the Lambda function will receive the entire request object.defaultRoute
handles incoming requests that don’t match any other route. In this case, it matches all requests.deployment
creates a new deployment of the API Gateway. This is required before we can create a stage.stage
represents a state of the API Gateway. In this case, it’s just thedev
stage but we could create multiple stages for different environments (e.g.prod
).- Finally,
url
is the URL of the API gateway combined with the stage name. This is the URL that clients can connect to.