Skip to content

Commit

Permalink
Merge pull request #118 from TNG/update-dependencies
Browse files Browse the repository at this point in the history
Update dependencies
  • Loading branch information
lukastaegert committed Sep 15, 2023
2 parents 6d808a8 + 721915e commit efbf249
Show file tree
Hide file tree
Showing 47 changed files with 7,198 additions and 4,991 deletions.
2 changes: 1 addition & 1 deletion .lintstagedrc
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"*.{js,ts,tsx}": "eslint --cache --fix --ext .js,.ts,.tsx",
"*.{css,md,json,html,yaml}": "prettier --write"
"*": "prettier --write"
}
45 changes: 20 additions & 25 deletions backend/local/dynamo.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,16 @@
import { AWSError, config, DynamoDB } from 'aws-sdk';
import { CreateTableOutput } from 'aws-sdk/clients/dynamodb';
import { DynamoDB } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocument } from '@aws-sdk/lib-dynamodb';
import { AWSError } from '../shared/types';

config.update(
{
region: 'local',
endpoint: 'http://localhost:8000',
credentials: { accessKeyId: 'accessKeyId', secretAccessKey: 'secretAccessKey' },
},
true
);
const dynamodb = new DynamoDB();

export const ddb = new DynamoDB.DocumentClient({
const dynamodb = new DynamoDB({
apiVersion: '2012-08-10',
region: 'local',
endpoint: 'http://localhost:8000',
credentials: { accessKeyId: 'accessKeyId', secretAccessKey: 'secretAccessKey' },
});

export const ddb = DynamoDBDocument.from(dynamodb);

const TableName = 'scrum-poker-local';

const params = {
Expand All @@ -29,16 +23,18 @@ const params = {
},
};

const createTable = () =>
new Promise((resolve, reject) =>
dynamodb.createTable(params, (error: AWSError, data: CreateTableOutput) => {
if (error) {
reject(error);
} else {
resolve(data);
}
})
);
const createTable = async () => {
try {
const tableData = await dynamodb.createTable(params);
console.log('Created table:', JSON.stringify(tableData, null, 2));
} catch (err) {
if (err && (err as AWSError).name === 'ResourceInUseException') {
console.log('Table already exists');
return;
}
throw err;
}
};

const DATABASE_WAIT_SECONDS = 60;

Expand All @@ -47,8 +43,7 @@ export const prepareTable = async () => {
const timeout = Date.now() + DATABASE_WAIT_SECONDS * 1000;
while (Date.now() < timeout) {
try {
const data = await createTable();
console.log('Created table:', JSON.stringify(data, null, 2));
await createTable();
return;
} catch (err) {
if (!(err instanceof Error)) {
Expand Down
28 changes: 17 additions & 11 deletions backend/local/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ import { generateId } from '../../shared/generateId';
import { onConnect } from '../onconnect/src/on-connect';
import { onDisconnect } from '../ondisconnect/src/on-disconnect';
import { onMessage } from '../sendmessage/src/on-message';
import { ConfigWithHandler } from '../shared/types';
import { ddb } from './dynamo';
import { Readable } from 'stream';

interface WebsocketWithId extends WebSocket {
id: string;
Expand All @@ -19,25 +21,29 @@ export const startWebSocketServer = () => {
const socketId = generateId(16);
(ws as WebsocketWithId).id = socketId;

const config = {
const config: ConfigWithHandler = {
connectionId: socketId,
tableName: 'scrum-poker-local',
ddb,
handler: {
postToConnection: ({ ConnectionId, Data }: { ConnectionId: string; Data: unknown }) => {
postToConnection: ({ ConnectionId, Data }) => {
// $metadata is required in the return type
if (!Data) return Promise.resolve({ $metadata: {} });
const client = [...wss.clients].find(
(client) => ConnectionId === (client as WebsocketWithId).id
(client) => ConnectionId === (client as WebsocketWithId).id,
);
const resultPromise = client
? new Promise<void>((resolve, reject) =>
client.send(Data, (error) => (error ? reject(error) : resolve()))
return client
? new Promise((resolve, reject) =>
client.send(
Data as Exclude<typeof Data, Readable | Blob | ReadableStream<unknown>>,
(error) => (error ? reject(error) : resolve({ $metadata: {} })),
),
)
: Promise.reject(
Object.assign(new Error(`Could not find client with id ${ConnectionId}`), {
statusCode: 410,
})
}),
);
return { promise: () => resultPromise };
},
},
};
Expand All @@ -47,19 +53,19 @@ export const startWebSocketServer = () => {
ws.on('close', () =>
onDisconnect(config)
.then((result) => console.log('Disconnected', socketId, result))
.catch((error) => console.error('Error disconnecting', error))
.catch((error) => console.error('Error disconnecting', error)),
);

ws.on('unexpected-response', (request, message) =>
console.error(`Unexpected socket response`, request, message)
console.error(`Unexpected socket response`, request, message),
);

ws.on('error', (error) => console.error('Socket error', error));

ws.on('message', (data) => {
const message = JSON.parse(String(data));
onMessage(message.data, config).catch((error) =>
console.error('Error processing message', error)
console.error('Error processing message', error),
);
});
});
Expand Down
13 changes: 8 additions & 5 deletions backend/onconnect/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { DynamoDB } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocument } from '@aws-sdk/lib-dynamodb';
import { APIGatewayProxyHandler } from 'aws-lambda/trigger/api-gateway-proxy';
import { DynamoDB } from 'aws-sdk';
import { captureException } from '../../shared/exceptions';
import { TABLE_NAME } from './const';
import { onConnect } from './on-connect';

const ddb = new DynamoDB.DocumentClient({
apiVersion: '2012-08-10',
region: process.env.AWS_REGION,
});
const ddb = DynamoDBDocument.from(
new DynamoDB({
apiVersion: '2012-08-10',
region: process.env.AWS_REGION,
}),
);

export const handler: APIGatewayProxyHandler = ({ requestContext: { connectionId } }) => {
if (!connectionId) {
Expand Down
16 changes: 10 additions & 6 deletions backend/ondisconnect/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import { ApiGatewayManagementApi } from '@aws-sdk/client-apigatewaymanagementapi';
import { DynamoDB } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocument } from '@aws-sdk/lib-dynamodb';
import { APIGatewayProxyHandler } from 'aws-lambda/trigger/api-gateway-proxy';
import { ApiGatewayManagementApi, DynamoDB } from 'aws-sdk';
import { captureException } from '../../shared/exceptions';
import { TABLE_NAME } from './const';
import { onDisconnect } from './on-disconnect';

const ddb = new DynamoDB.DocumentClient({
apiVersion: '2012-08-10',
region: process.env.AWS_REGION,
});
const ddb = DynamoDBDocument.from(
new DynamoDB({
apiVersion: '2012-08-10',
region: process.env.AWS_REGION,
}),
);

export const handler: APIGatewayProxyHandler = ({
requestContext: { connectionId, domainName },
Expand All @@ -21,7 +25,7 @@ export const handler: APIGatewayProxyHandler = ({
tableName: TABLE_NAME,
handler: new ApiGatewayManagementApi({
apiVersion: '2018-11-29',
endpoint: domainName,
endpoint: `https://${domainName}`,
}),
});
};
1 change: 1 addition & 0 deletions backend/ondisconnect/src/on-disconnect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export const onDisconnect = async (config: ConfigWithHandler) => {
try {
await removeConnection(config);
} catch (err) {
console.error('Failed to disconnect: ' + JSON.stringify(err));
return { statusCode: 500, body: 'Failed to disconnect: ' + JSON.stringify(err) };
}

Expand Down
8 changes: 6 additions & 2 deletions backend/rollup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,17 @@ export default defineConfig(
const lambdaPath = join(__dirname, lambdaName);
return {
input: join(lambdaPath, 'src/app.ts'),
external: ['aws-sdk'],
external: [
'@aws-sdk/client-apigatewaymanagementapi',
'@aws-sdk/client-dynamodb',
'@aws-sdk/lib-dynamodb',
],
plugins: [typescript({ tsconfig: join(lambdaPath, 'tsconfig.json') })],
output: {
file: join(lambdaPath, 'build/app.js'),
format: 'cjs' as const,
interop: 'default' as const,
},
};
})
}),
);
16 changes: 10 additions & 6 deletions backend/sendmessage/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import { ApiGatewayManagementApi } from '@aws-sdk/client-apigatewaymanagementapi';
import { DynamoDB } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocument } from '@aws-sdk/lib-dynamodb';
import { APIGatewayProxyHandler } from 'aws-lambda';
import { ApiGatewayManagementApi, DynamoDB } from 'aws-sdk';
import { captureException } from '../../shared/exceptions';
import { TABLE_NAME } from './const';
import { onMessage } from './on-message';

const ddb = new DynamoDB.DocumentClient({
apiVersion: '2012-08-10',
region: process.env.AWS_REGION,
});
const ddb = DynamoDBDocument.from(
new DynamoDB({
apiVersion: '2012-08-10',
region: process.env.AWS_REGION,
}),
);

export const handler: APIGatewayProxyHandler = ({
requestContext: { connectionId, domainName },
Expand All @@ -23,7 +27,7 @@ export const handler: APIGatewayProxyHandler = ({
ddb,
handler: new ApiGatewayManagementApi({
apiVersion: '2018-11-29',
endpoint: domainName,
endpoint: `https://${domainName}`,
}),
});
};
4 changes: 2 additions & 2 deletions backend/sendmessage/src/login-user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const loginUser = async (userId: string, groupId: string, config: ConfigW
groupId,
userId,
groupItem.connections[userId]?.vote || VOTE_NOTE_VOTED,
config
config,
)
: createGroupWithConnection(groupId, userId, getTtl(EXPIRY_TIME_IN_HOUR), config);

Expand All @@ -29,7 +29,7 @@ export const loginUser = async (userId: string, groupId: string, config: ConfigW
type: 'not-logged-in',
payload: { reason: 'Your session was taken over by another user with the same name.' },
},
{ ...config, connectionId: userConnectionId }
{ ...config, connectionId: userConnectionId },
);
}

Expand Down
2 changes: 1 addition & 1 deletion backend/sendmessage/src/remove-user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const removeUser = async (user: string, config: ConfigWithHandler): Promi
userConnectionId &&
sendMessageToConnection(
{ type: 'not-logged-in', payload: { reason: `You have been kicked by ${userId}.` } },
{ ...config, connectionId: userConnectionId }
{ ...config, connectionId: userConnectionId },
),
]);
}
Expand Down
23 changes: 10 additions & 13 deletions backend/shared/actions.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { AWSError } from 'aws-sdk';
import { ServerMessage, Votes } from '../../shared/serverMessages';
import { deleteConnection } from './database/deleteConnection';
import { getConnection } from './database/getConnection';
import { removeConnectionFromGroup } from './database/removeConnectionFromGroup';
import { ConfigWithHandler, GroupItem } from './types';
import { AWSError, ConfigWithHandler, GroupItem } from './types';

export const broadcastState = async (
{ connections, visible, scale }: GroupItem,
config: ConfigWithHandler
config: ConfigWithHandler,
): Promise<unknown> => {
const connectionEntries = Object.entries(connections);
const votes: Votes = {};
Expand Down Expand Up @@ -35,24 +34,22 @@ export const broadcastState = async (
{
...config,
connectionId,
}
)
)
},
),
),
);
};

export const sendMessageToConnection = async (
message: ServerMessage,
config: ConfigWithHandler
config: ConfigWithHandler,
): Promise<unknown> => {
const { handler, connectionId } = config;
try {
await handler
.postToConnection({
ConnectionId: connectionId,
Data: JSON.stringify(message),
})
.promise();
await handler.postToConnection({
ConnectionId: connectionId,
Data: Buffer.from(JSON.stringify(message)),
});
} catch (e) {
if (e && (e as AWSError).statusCode === 410) {
return removeConnection(config);
Expand Down
36 changes: 17 additions & 19 deletions backend/shared/database/addConnectionToGroup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,24 @@ export const addConnectionToGroup = async (
groupId: string,
userId: string,
vote: CardValue,
{ ddb, tableName, connectionId }: Config
{ ddb, tableName, connectionId }: Config,
): Promise<GroupItem> =>
(
await ddb
.update({
TableName: tableName,
Key: {
primaryKey: `groupId:${groupId}`,
await ddb.update({
TableName: tableName,
Key: {
primaryKey: `groupId:${groupId}`,
},
UpdateExpression: `SET connections.#userId = :connection`,
ExpressionAttributeNames: {
'#userId': userId,
},
ExpressionAttributeValues: {
':connection': {
connectionId,
vote,
},
UpdateExpression: `SET connections.#userId = :connection`,
ExpressionAttributeNames: {
'#userId': userId,
},
ExpressionAttributeValues: {
':connection': {
connectionId,
vote,
},
},
ReturnValues: 'ALL_NEW',
})
.promise()
},
ReturnValues: 'ALL_NEW',
})
).Attributes as GroupItem;
Loading

0 comments on commit efbf249

Please sign in to comment.