-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathjoin-game.js
More file actions
84 lines (76 loc) · 2.5 KB
/
join-game.js
File metadata and controls
84 lines (76 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const AWS = require('aws-sdk');
const ddb = new AWS.DynamoDB.DocumentClient();
require('./join-patch.js');
let send = undefined;
const TABLE_NAME = "game-session";
const PLAYING_OP = "11";
function init(event) {
const apigwManagementApi = new AWS.ApiGatewayManagementApi({
apiVersion: '2018-11-29',
endpoint: event.requestContext.domainName + '/' + event.requestContext.stage
});
send = async (connectionId, data) => {
await apigwManagementApi.postToConnection({
ConnectionId: connectionId,
Data: `${data}`
}).promise();
}
}
function getAvailableGameSession() {
return ddb.scan({
TableName: TABLE_NAME,
FilterExpression: "#p2 = :empty and #status <> :closed",
ExpressionAttributeNames: {
"#p2": "player2",
"#status": "gameStatus"
},
ExpressionAttributeValues: {
":empty": "empty",
":closed": "closed"
}
}).promise();
}
function addConnectionId(connectionId) {
return getAvailableGameSession().then((data) => {
console.log("Game session data: %j", data);
if (data && data.Count < 1) {
// create new game session
console.log("No sessions exist, creating session...");
return ddb.put({
TableName: TABLE_NAME,
Item: {
uuid: Date.now() + '', // dont do this, use a uuid generation library
player1: connectionId,
player2: "empty"
},
}).promise();
} else {
// add player to existing session as player2
console.log("Session exists, adding player2 to existing session");
return ddb.update({
TableName: TABLE_NAME,
Key: {
"uuid": data.Items[0].uuid // just grap the first result, as there should only be one
},
UpdateExpression: "set player2 = :p2",
ExpressionAttributeValues: {
":p2": connectionId
}
}).promise().then(() => {
// inform player 1 game started. Cannot yet send message to player2.
send(data.Items[0].player1, '{ "uuid": ' + data.Items[0].uuid + ', "opcode": ' + PLAYING_OP +
' }');
});
}
});
}
exports.handler = (event, context, callback) => {
const connectionId = event.requestContext.connectionId;
console.log("Connect event received: %j", event);
init(event);
addConnectionId(connectionId).then(() => {
callback(null, {
statusCode: 200
});
});
}