init new sub project, backend

This commit is contained in:
2025-06-18 00:29:57 +09:00
parent ec43ccf6c8
commit 215c0d72fd
12 changed files with 3016 additions and 7 deletions

48
backend/src/index.ts Normal file
View 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);
}
};