Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement dynamodb on each route #32

Open
wants to merge 3 commits into
base: session-3-v3
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 14 additions & 14 deletions backend/serverless.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// import { Stack } from '@aws-cdk/core';
import { app, stack/*, table*/ } from '@resources/index';
import { Stack } from '@aws-cdk/core';
import { app, stack, table } from '@resources/index';

import { functions } from '@functions/index';

Expand Down Expand Up @@ -30,18 +30,18 @@ const serverlessConfiguration: AWS = {
},
},
},
// iamRoleStatements: [
// {
// Effect: 'Allow',
// Action: [
// 'dynamodb:Query',
// 'dynamodb:PutItem',
// 'dynamodb:DeleteItem',
// 'dynamodb:ListStreams',
// ],
// Resource: [Stack.of(stack).resolve(table.tableArn)],
// },
// ],
iamRoleStatements: [
{
Effect: 'Allow',
Action: [
'dynamodb:Query',
'dynamodb:PutItem',
'dynamodb:DeleteItem',
'dynamodb:ListStreams',
],
Resource: [Stack.of(stack).resolve(table.tableArn)],
},
],
logs: {
restApi: true,
},
Expand Down
8 changes: 7 additions & 1 deletion backend/src/functions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,16 @@ import hello from './hello';
import getVirus from './virus-get';
import killVirus from './virus-kill';
import createVirus from './virus-create';
import wsConnect from './ws-connect';
import wsDisconnect from './ws-disconnect';
import sendMessageToClient from './sendMessageToClient';

export const functions = {
hello,
getVirus,
killVirus,
createVirus
createVirus,
wsConnect,
wsDisconnect,
sendMessageToClient
};
35 changes: 35 additions & 0 deletions backend/src/functions/sendMessageToClient/handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { DynamoDBStreamEvent } from 'aws-lambda';
import { Converter } from 'aws-sdk/clients/dynamodb';
import { getAllConnections } from '@libs/connections';
import { sendMessageToConnection } from '@libs/websocket';
import { Item } from '@libs/types';
import { Virus } from '@functions/types';

const sendMessageToEachConnection = async (message: any): Promise<void> => {
const connections = await getAllConnections();
await Promise.all(
connections.map(({ connectionId, endpoint }) => {
sendMessageToConnection({
connectionId,
endpoint,
message,
});
}
),
);
};

const isVirus = (item: Item): item is Virus => item.partitionKey === 'Virus';

export const main = async (event: DynamoDBStreamEvent): Promise<void> => {
await Promise.all(
event.Records.map(({ eventName, dynamodb }) => {
if (eventName === 'INSERT' && dynamodb && dynamodb.NewImage) {
const newItem = Converter.unmarshall(dynamodb.NewImage) as Item;
if (isVirus(newItem)) {
return sendMessageToEachConnection({ virusId: newItem.sortKey });
}
}
}),
);
};
17 changes: 17 additions & 0 deletions backend/src/functions/sendMessageToClient/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Stack } from '@aws-cdk/core';
import { stack, table } from '@resources/index';
import { handlerPath } from '@libs/handlerResolver';

export default {
handler: `${handlerPath(__dirname)}/handler.main`,
events: [
{
stream: {
// @ts-ignore
type: 'dynamodb',
// @ts-ignore
arn: Stack.of(stack).resolve(table.tableStreamArn),
},
},
],
}
20 changes: 17 additions & 3 deletions backend/src/functions/virus-create/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,25 @@ import { formatJSONResponse } from '@libs/apiGateway';
import { APIGatewayProxyHandler } from 'aws-lambda';
import { middyfyWithoutBodyParser } from '@libs/lambda';
import uuid from 'uuid';
import {
PutCommand,
DynamoDBDocumentClient
} from '@aws-sdk/lib-dynamodb';
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';

const create: APIGatewayProxyHandler = async () => {
const documentClient = DynamoDBDocumentClient.from(new DynamoDBClient({}));

const kill: APIGatewayProxyHandler = async () => {
const id = uuid();
console.log('Virus created');

await documentClient.send(
new PutCommand({
TableName: 'dojo-serverless-table',
Item: { partitionKey: 'Virus', sortKey: id },
}),
);

return formatJSONResponse({ id });
}

export const main = middyfyWithoutBodyParser(create);
export const main = middyfyWithoutBodyParser(kill);
24 changes: 16 additions & 8 deletions backend/src/functions/virus-get/handler.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
import { formatJSONResponse } from '@libs/apiGateway';
import { Virus } from '../types';
import { APIGatewayProxyHandler } from 'aws-lambda';
import { middyfyWithoutBodyParser } from '@libs/lambda';
import uuid from 'uuid';
import {
QueryCommand,
DynamoDBDocumentClient
} from '@aws-sdk/lib-dynamodb';
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';

const documentClient = DynamoDBDocumentClient.from(new DynamoDBClient({}));

const get: APIGatewayProxyHandler = async () => {
const viruses = [
{ id: uuid() },
{ id: uuid() },
{ id: uuid() },
{ id: uuid() },
];
return formatJSONResponse({ viruses });
const { Items = [] } = await documentClient.send(
new QueryCommand({
TableName: 'dojo-serverless-table',
KeyConditionExpression: 'partitionKey = :partitionKey',
ExpressionAttributeValues: { ':partitionKey': 'Virus' },
}),
);
return formatJSONResponse({ viruses: (Items as Virus[]).map(({ sortKey }) => ({ id: sortKey })) });
}

export const main = middyfyWithoutBodyParser(get);
14 changes: 14 additions & 0 deletions backend/src/functions/virus-kill/handler.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,23 @@
import { middyfyWithoutBodyParser } from '@libs/lambda';
import { formatJSONResponse, IdParamRequiredEventAPIGatewayProxyHandler } from '@libs/apiGateway';
import {
DeleteCommand,
DynamoDBDocumentClient
} from '@aws-sdk/lib-dynamodb';
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';

const documentClient = DynamoDBDocumentClient.from(new DynamoDBClient({}));

const kill: IdParamRequiredEventAPIGatewayProxyHandler = async (event) => {
const { id } = event.pathParameters;

await documentClient.send(
new DeleteCommand({
TableName: 'dojo-serverless-table',
Key: { partitionKey: 'Virus', sortKey: id },
}),
);

console.log('Virus killed');
return formatJSONResponse({ id });
}
Expand Down
9 changes: 9 additions & 0 deletions backend/src/functions/ws-connect/handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { formatJSONResponse } from '@libs/apiGateway';
import { WebSocketConnectRequestEvent, extractEndpointFromEvent } from '@libs/websocket';
import { createConnection } from '@libs/connections';

export const main = async (event: WebSocketConnectRequestEvent) => {
const endpoint = extractEndpointFromEvent(event);
await createConnection(event.requestContext.connectionId, endpoint);
return formatJSONResponse({});
}
12 changes: 12 additions & 0 deletions backend/src/functions/ws-connect/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { handlerPath } from '@libs/handlerResolver';

export default {
handler: `${handlerPath(__dirname)}/handler.main`,
events: [
{
websocket: {
route: '$connect'
}
}
]
}
8 changes: 8 additions & 0 deletions backend/src/functions/ws-disconnect/handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { formatJSONResponse } from '@libs/apiGateway';
import { WebSocketDisconnectRequestEvent } from '@libs/websocket';
import { deleteConnection } from '@libs/connections';

export const main = async (event: WebSocketDisconnectRequestEvent) => {
await deleteConnection(event.requestContext.connectionId);
return formatJSONResponse({});
}
12 changes: 12 additions & 0 deletions backend/src/functions/ws-disconnect/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { handlerPath } from '@libs/handlerResolver';

export default {
handler: `${handlerPath(__dirname)}/handler.main`,
events: [
{
websocket: {
route: '$disconnect'
}
}
]
}
9 changes: 6 additions & 3 deletions backend/src/libs/websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,22 @@ export const sendMessageToConnection = async ({
endpoint: string;
message: any;
}): Promise<void> => {
const apiGatewayCLient = new ApiGatewayManagementApiClient({
const apiGatewayClient = new ApiGatewayManagementApiClient({
apiVersion: '2018-11-29',
endpoint,
endpoint: `https://${endpoint.slice(0, endpoint.length - 4)}`,
});
try {
await apiGatewayCLient.send(
console.log('(1)(1) apiGatewayClient', apiGatewayClient);
await apiGatewayClient.send(
new PostToConnectionCommand({
ConnectionId: connectionId,
Data: Buffer.from(JSON.stringify(message)),
}),
);
console.log('(1)(2)');
} catch (error) {
if (error.statusCode !== 410) {
console.log('(error)');
throw error;
}
console.log(`Found stale connection, deleting ${connectionId}`);
Expand Down
4 changes: 2 additions & 2 deletions backend/src/resources/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { App, Stack } from '@aws-cdk/core';
// import initDynamodb from './dynamodb';
import initDynamodb from './dynamodb';
import initApiGatewayErrors from './apiGatewayErrors';

export const app = new App();
export const stack = new Stack(app, 'Stack');

// export const table = initDynamodb(stack);
export const table = initDynamodb(stack);
initApiGatewayErrors(stack);
14 changes: 13 additions & 1 deletion frontend/src/pages/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import virus4 from 'assets/Virus4.png';
import virus5 from 'assets/Virus5.png';
import virus6 from 'assets/Virus6.png';

import { websocketConnexion } from '../services/networking/websocket';

const VirusImgs = [virus1, virus2, virus3, virus4, virus5, virus6];

const { Title, Text } = Typography;
Expand Down Expand Up @@ -77,7 +79,7 @@ export default () => {
{ method: 'POST' },
);
const { id } = await response.json();
setViruses((prevViruses) => prevViruses.concat(getRandomVirus(id)));
// setViruses((prevViruses) => prevViruses.concat(getRandomVirus(id)));
};

const killVirus = async (virusId: string) => {
Expand All @@ -88,6 +90,16 @@ export default () => {
setViruses((prevViruses) => prevViruses.filter(({ id }) => id !== virusId));
};

websocketConnexion.onmessage = (message) => {
const data = JSON.parse(message.data);
const virusId = data.virusId;
console.log('message', message);
console.log('virusId', virusId);
if (virusId) {
setViruses((prevViruses) => prevViruses.concat(getRandomVirus(virusId)));
}
};

return (
<>
<AddVirusButton
Expand Down