-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresponse.js
More file actions
102 lines (83 loc) · 2.49 KB
/
response.js
File metadata and controls
102 lines (83 loc) · 2.49 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
'use strict'
const Transports = require('./transports')
module.exports = {
addRemoteFunction: addRemoteFunction,
flexRequest: flexRequest,
}
function addRemoteFunction(fn, fnName) {
// Allow first or second param to be the string for the name over-ride.
if (typeof fn === 'string') {
const arg1 = fn, arg2 = fnName
fn = arg2
fnName = arg1
}
// If an array of functions are given
if (typeof fn === 'object' && Array.isArray(fn)) {
const fnList = fn
for (let fn of fnList) {
// Allow anonymous/arrow functions to nest array.
/* Example: flex.add([
[() => {}, 'something1'],
[() => {}, 'something2'],
]) */
if (typeof fn === 'object' && Array.isArray(fn) && fn.length > 1)
addRemoteFunction.call(this, fn[0], fn[1])
else
addRemoteFunction.call(this, fn)
}
return
}
if (typeof fn !== 'function')
throw new Error('Must be a function')
if (!fnName || typeof fnName !== 'string')
fnName = fn.name
if (!fnName)
throw new Error('Anonymous/Arrow functions are not supported without a label in Flex!')
if (this.functions[fnName])
throw new Error(`'${fnName}' Function already added to Flex!`)
this.functions[fnName] = fn
}
function flexRequest(rpcRequest) {
console.log('Incomming rpcRequest:', rpcRequest)
// Now we do the inverse and call the function on the server side.
let rpcAnswer = {
id: rpcRequest.id,
req: rpcRequest.req,
//args: ['success'],
}
try {
const fn = this.functions[rpcRequest.req]
if (!fn) {
rpcAnswer.error = 'No Such Function'
return rpcAnswer
}
// Merge the rpcRequest args and callback params in the correct order.
const fnParams = rpcRequest.args
for (let param of rpcRequest.callbacks) {
// Wrap callback functions. (May cause problems with non-streaming architectures)
const cbFunction = proxyCallbackFunction(rpcRequest, param.index)
fnParams.splice(param.index, 1, cbFunction)
}
rpcAnswer.result = fn.apply(null, rpcRequest.args)
} catch (err) {
rpcAnswer.error = err.message
}
console.log('rpcAnswer:')
console.log(rpcAnswer)
return rpcAnswer
}
function proxyCallbackFunction(rpcRequest, cid) {
return function proxiedCallback() {
const message = {
event: 'rpcAnswerCallback',
data: {
id: rpcRequest.id,
req: rpcRequest.req,
args: arguments,
cid: cid,
status: 'pending',
}
}
Transports.send(message)
}
}