45 lines
1.4 KiB
TypeScript
45 lines
1.4 KiB
TypeScript
import { ApiGatewayManagementApiClient, PostToConnectionCommand } from "@aws-sdk/client-apigatewaymanagementapi";
|
|
import { APIGatewayProxyHandlerV2 } from "aws-lambda";
|
|
|
|
export const main: APIGatewayProxyHandlerV2 = async (event) => {
|
|
const body = event.body;
|
|
const {domainName, stage, connectionId, routeKey} = event.requestContext;
|
|
|
|
const apiGateway = new ApiGatewayManagementApiClient({
|
|
endpoint: `https://${domainName}/${stage}`,
|
|
});
|
|
|
|
try {
|
|
switch (routeKey) {
|
|
case '$connect':
|
|
return { statusCode: 200, body: 'Connected' };
|
|
|
|
case '$disconnect':
|
|
return { statusCode: 200, body: 'Disconnected' };
|
|
|
|
default:
|
|
console.log(`Received message: ${body}`);
|
|
await sendMessageToClient(apiGateway, connectionId, `Echo: ${body}`);
|
|
return { statusCode: 200, body: `Echoed: ${body}` };
|
|
}
|
|
} catch (error) {
|
|
console.error('Error: ', error);
|
|
return { statusCode: 500, body: 'Error processing request' };
|
|
}
|
|
};
|
|
|
|
// メッセージをクライアントに送信する関数(修正済み)
|
|
const sendMessageToClient = async (apiGateway, connectionId, message) => {
|
|
try {
|
|
const command = new PostToConnectionCommand({
|
|
ConnectionId: connectionId,
|
|
Data: Buffer.from(message),
|
|
});
|
|
|
|
await apiGateway.send(command);
|
|
console.log(`Sent message to ${connectionId}: ${message}`);
|
|
} catch (error) {
|
|
console.error(`Failed to send message to ${connectionId}:`, error);
|
|
}
|
|
};
|