-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathwebsockets.js
93 lines (85 loc) · 2.84 KB
/
websockets.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
// Import and load env files
AutoLoad = require("@njs2/base/base/autoload.class");
AutoLoad.loadConfig();
AutoLoad.loadModules();
// Import Executor class
const { sockets, Executor } = require("@njs2/base");
const {
CONNECTION_HANDLER_METHOD,
DISCONNECTION_HANDLER_METHOD,
} = require("./src/global/constants");
const executeRequests = async (connectionId, wsEvent, request_id) => {
const executor = new Executor();
const resp = await executor.executeRequest(wsEvent);
if (request_id)
await sockets.emit(connectionId, { request_id: request_id, body: resp });
};
module.exports.handler = async (event) => {
const body =
typeof event.body == "string" ? JSON.parse(event.body) : event.body;
const requestId = body ? body.request_id : null;
try {
let wsEvent = {};
switch (event.requestContext.eventType) {
case "CONNECT":
wsEvent.httpMethod = "GET";
wsEvent.requestId = null;
wsEvent.headers = event.queryStringParameters.access_token
? {
access_token: event.queryStringParameters.access_token,
}
: {};
wsEvent.pathParameters = {
proxy: CONNECTION_HANDLER_METHOD,
};
delete event.queryStringParameters.access_token;
wsEvent.queryStringParameters = {
socket_id: event.requestContext.connectionId,
...event.queryStringParameters,
};
CONNECTION_HANDLER_METHOD &&
(await executeRequests(event.requestContext.connectionId, wsEvent));
break;
case "DISCONNECT":
wsEvent.httpMethod = "GET";
wsEvent.requestId = null;
wsEvent.headers = {};
wsEvent.pathParameters = {
proxy: DISCONNECTION_HANDLER_METHOD,
};
wsEvent.queryStringParameters = {
socket_id: event.requestContext.connectionId,
};
DISCONNECTION_HANDLER_METHOD &&
(await executeRequests(event.requestContext.connectionId, wsEvent));
break;
case "MESSAGE":
wsEvent.httpMethod = body.method;
wsEvent.requestId = body.request_id;
wsEvent.headers =
body.headers && typeof body.headers == "object" ? body.headers : {};
wsEvent.pathParameters = {
proxy: body.action,
};
if (body.method == "GET") {
wsEvent.queryStringParameters = body.body;
} else if (body.method == "POST") {
wsEvent.body = body.body;
}
await executeRequests(
event.requestContext.connectionId,
wsEvent,
requestId
);
break;
}
return { statusCode: 200, body: "SUCCESS" };
} catch (e) {
console.log(e);
await sockets.emit(event.requestContext.connectionId, {
request_id: requestId,
error: "Invalid Request",
});
return { statusCode: 500, body: "Internal server error" };
}
};