Skip to content

WebSocketEventSource

Source: src/AWS/ApiGatewayV2/WebSocketEventSource.ts

Event source connecting a WebSocket Api route to the hosting Lambda function.

At deploy time the Lambda implementation (Lambda.WebSocketEventSource) materializes the Integration, Route, and invoke Permission for the route; at runtime it dispatches matching WebSocket proxy events to the handler. Subscribe routes with onWebSocketRoute and provide Lambda.WebSocketEventSource on the hosting function.

export default MyFunction.make(
{ main: import.meta.url },
Effect.gen(function* () {
const api = yield* ApiGatewayV2.Api("WsApi", {
protocolType: "WEBSOCKET",
routeSelectionExpression: "$request.body.action",
});
const stage = yield* ApiGatewayV2.Stage("WsStage", {
api,
stageName: "prod",
autoDeploy: true,
});
const connections = yield* ApiGatewayV2.ManageConnections(stage);
yield* ApiGatewayV2.onWebSocketRoute(api, { routeKey: "$connect" }, () =>
Effect.succeed({ statusCode: 200 }),
);
yield* ApiGatewayV2.onWebSocketRoute(api, { routeKey: "$default" }, (event) =>
connections
.postToConnection({
ConnectionId: event.requestContext.connectionId,
Data: `echo:${event.body ?? ""}`,
})
.pipe(
Effect.asVoid,
Effect.catchTag("GoneException", () => Effect.void),
Effect.orDie,
),
);
return {};
}).pipe(
Effect.provide(
Layer.mergeAll(
Lambda.WebSocketEventSource,
ApiGatewayV2.ManageConnectionsHttp,
),
),
),
);