-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathsocketio.js
69 lines (59 loc) · 2.5 KB
/
socketio.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
AutoLoad = require('@njs2/base/base/autoload.class');
AutoLoad.loadConfig();
AutoLoad.loadModules();
const { Executor, sockets } = require("@njs2/base");
sockets.init();
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.access_token?{access_token:event.access_token}:{};
wsEvent.pathParameters = {
proxy: CONNECTION_HANDLER_METHOD
};
wsEvent.queryStringParameters = { socket_id: event.requestContext.connectionId,...event.queryData }
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' };
}
}