init new sub project, backend
This commit is contained in:
48
backend/src/index.ts
Normal file
48
backend/src/index.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
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}`,
|
||||
});
|
||||
|
||||
console.log("Received event: ", JSON.stringify(event, null, 2));
|
||||
|
||||
try {
|
||||
switch (routeKey) {
|
||||
case '$connect':
|
||||
console.log(`New connection: ${connectionId}`);
|
||||
return { statusCode: 200, body: 'Connected' };
|
||||
|
||||
case '$disconnect':
|
||||
console.log(`Disconnected: ${connectionId}`);
|
||||
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);
|
||||
}
|
||||
};
|
Reference in New Issue
Block a user