forked from dherault/serverless-offline
/
handler.js
113 lines (92 loc) · 4.53 KB
/
handler.js
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
'use strict';
const AWS = require('aws-sdk');
const ddb = (()=>{
if (process.env.IS_OFFLINE) return new AWS.DynamoDB.DocumentClient({region: "localhost", endpoint: "http://localhost:8000"});
return new AWS.DynamoDB.DocumentClient();
})();
const successfullResponse = {
statusCode: 200,
body: 'Request is OK.'
};
const errorResponse = {
statusCode: 400,
body: 'Request is not OK.'
};
// module.exports.http = async (event, context) => {
// return successfullResponse;
// };
module.exports.connect = async (event, context) => {
const listener=await ddb.get({TableName:'listeners', Key:{name:'default'}}).promise();
if (listener.Item) {
const timeout=new Promise((resolve) => setTimeout(resolve,100));
const send=sendToClient( // sendToClient won't return on AWS when client doesn't exits so we set a timeout
JSON.stringify({action:'update', event:'connect', info:{id:event.requestContext.connectionId, queryStringParameters:event.queryStringParameters}}),
listener.Item.id,
newAWSApiGatewayManagementApi(event, context)).catch(()=>{});
await Promise.race([send, timeout]);
}
return successfullResponse;
};
module.exports.disconnect = async (event, context) => {
const listener=await ddb.get({TableName:'listeners', Key:{name:'default'}}).promise();
if (listener.Item) await sendToClient(JSON.stringify({action:'update', event:'disconnect', info:{id:event.requestContext.connectionId}}), listener.Item.id, newAWSApiGatewayManagementApi(event, context)).catch(()=>{});
return successfullResponse;
};
module.exports.defaultHandler = async (event, context) => {
await sendToClient(`Error: No Supported Action in Payload '${event.body}'`, event.requestContext.connectionId, newAWSApiGatewayManagementApi(event, context)).catch(err=>console.log(err));
return successfullResponse;
};
module.exports.getClientInfo = async (event, context) => {
await sendToClient({action:'update', event:'client-info', info:{id:event.requestContext.connectionId}}, event.requestContext.connectionId, newAWSApiGatewayManagementApi(event, context)).catch(err=>console.log(err));
return successfullResponse;
};
module.exports.makeError = async (event, context) => {
const obj=null;
obj.non.non=1;
return successfullResponse;
};
module.exports.multiCall1 = async (event, context) => {
await sendToClient({action:'update', event:'made-call-1'}, event.requestContext.connectionId, newAWSApiGatewayManagementApi(event, context)).catch(err=>console.log(err));
return successfullResponse;
};
module.exports.multiCall2 = async (event, context) => {
await sendToClient({action:'update', event:'made-call-2'}, event.requestContext.connectionId, newAWSApiGatewayManagementApi(event, context)).catch(err=>console.log(err));
return successfullResponse;
};
module.exports.send = async (event, context) => {
const action = JSON.parse(event.body);
const sents=[];
action.clients.forEach((connectionId)=>{
const sent=sendToClient(action.data, connectionId, newAWSApiGatewayManagementApi(event, context));
sents.push(sent);
});
const noErr=await Promise.all(sents).then(()=>true).catch(()=>false);
if (!noErr) await sendToClient('Error: Could not Send all Messages', event.requestContext.connectionId, newAWSApiGatewayManagementApi(event, context));
return successfullResponse;
};
module.exports.registerListener = async (event, context) => {
await ddb.put({TableName:'listeners', Item:{name:'default', id:event.requestContext.connectionId}}).promise();
await sendToClient({action:'update', event:'register-listener', info:{id:event.requestContext.connectionId}}, event.requestContext.connectionId, newAWSApiGatewayManagementApi(event, context)).catch(err=>console.log(err));
return successfullResponse;
};
module.exports.deleteListener = async (event, context) => {
await ddb.delete({TableName:'listeners', Key:{name:'default'}}).promise();
return successfullResponse;
};
const newAWSApiGatewayManagementApi=(event, context)=>{
const endpoint=event.requestContext.domainName+'/'+event.requestContext.stage;
const apiVersion='2018-11-29';
let API=null;
if (!process.env.IS_OFFLINE) {
API = AWS;
require('aws-sdk/clients/apigatewaymanagementapi');
} else {
API = require('serverless-offline').AWS;
}
return new API.ApiGatewayManagementApi({ apiVersion, endpoint });
};
const sendToClient = (data, connectionId, apigwManagementApi) => {
let sendee=data;
if ('object'==typeof data) sendee=JSON.stringify(data);
return apigwManagementApi.postToConnection({ConnectionId: connectionId, Data: sendee}).promise();
};