-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
175 lines (149 loc) · 4.72 KB
/
Copy pathserver.js
File metadata and controls
175 lines (149 loc) · 4.72 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
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
/*
* Copyright (c) 2018, Simone A. Coelho - Optimizely
*
* Module: ds_rpc
* File Name: server.js
* Last Modified: 11/17/18 2:12 PM
*
*/
'use strict';
const http = require('http');
const url = require('url');
const methods = require('./rpc/methods');
const types = require('./types/types');
const server_config = require('./configuration/config').server;
const optimizely = require('./optimizely/optimizely_manager');
let server = http.createServer(requestListener);
const PORT = server_config.NODE_PORT;
// Initialize and get the datafile on server start
let appOptlyInstance;
optimizely.getInstance().then(optly => {
appOptlyInstance = optly;
}).catch(function() {
console.error('Unable to instantiate the Optimizely client');
});
let routes = {
/**
* Defines the different url paths that our application will respond to. This is
* the RPC endpoint and every operation/method request will come through here.
*
* @param body
* The JSON object in the request body that represents an individual function or method.
* @returns {Promise<object>}
* Original JSON object with corresponding result(s) appended.
*/
'/rpc': function(body) {
return new Promise((resolve, reject) => {
let _json = JSON.parse(body); // might throw error
let keys = Object.keys(_json);
let promiseArr = [];
if (!body) {
response.statusCode = 400;
//noinspection
// NodeModulesDependencies,NodeModulesDependencies,ES6ModulesDependencies,JSUnresolvedFunction
response.end(JSON.stringify(
{Message: `RPC request was expecting some data...!`}));
return;
}
for (let key of keys) {
if (methods[key] && typeof (methods[key].exec) === 'function') {
let execPromise = methods[key].exec.call(null, _json[key]);
if (!(execPromise instanceof Promise)) {
throw new Error(`exec on ${key} did not return a promise`);
}
promiseArr.push(execPromise);
} else {
let execPromise = Promise.resolve({
error: 'method is not defined',
});
promiseArr.push(execPromise);
}
}
Promise.all(promiseArr).then(iter => {
console.log(iter);
let response = {};
iter.forEach((val, index) => {
response[keys[index]] = val;
});
resolve(response);
}).catch(err => {
reject('RPC method - ' + err);
});
});
},
/**
* Describe endpoint, scans through the descriptions of both the methods
* and the data types, and returns that information in the response.
*
* @returns {Promise<object>}
* JSON Object with the descriptions for all the methods supported.
*/
'/describe': function() {
// load the type descriptions
return new Promise(resolve => {
let type;
let method = {};
// set types
type = types;
//set methods
for (let m in methods) {
method[m] = JSON.parse(JSON.stringify(methods[m]));
}
resolve({
types: type,
methods: method,
});
});
},
};
/**
* This function is called every time there is a new request, we wait on the data
* coming in, after which, we look at the path, and match it to a handler on the routing table.
*
* @param request
* @param response
*/
function requestListener(request, response) {
let reqUrl = `http://${request.headers.host}${request.url}`;
let parseUrl = url.parse(reqUrl, true);
let pathname = parseUrl.pathname;
// we're doing everything as json
response.setHeader('Content-Type', 'application/json');
// buffer for incoming data
let buf = null;
// listen for incoming data
request.on('data', data => {
if (buf === null) {
buf = data;
} else {
buf = buf + data;
}
});
// on end proceed with compute
request.on('end', () => {
let body = buf !== null ? buf.toString() : null;
if (routes[pathname]) {
let compute = routes[pathname].call(null, body);
if (!(compute instanceof Promise)) {
response.statusCode = 500;
response.end(
JSON.stringify({Message: 'Server error: Invalid Promise'}));
console.warn('Whatever I got from the RPC was not a Promise!');
} else {
compute.then(res => {
response.end(JSON.stringify(res));
}).catch(err => {
console.error(err);
response.statusCode = 500;
response.end(JSON.stringify({Message: 'Server error: ' + err}));
});
}
} else {
response.statusCode = 404;
response.end(
JSON.stringify({'Message': `Error: ${pathname} not found here`}));
}
});
}
console.log(`Starting the server on port ${PORT}`);
server.listen(PORT);