forked from artemyarulin/react-native-eval
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRNMEvaluator.js
63 lines (53 loc) · 1.8 KB
/
RNMEvaluator.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
/**
*
* @providesModule RNMEvaluator
* @flow
*/
'use strict';
var {
DeviceEventEmitter,
NativeModules: {
RNMEvaluator
}
} = require('react-native');
var execute = (data, executor) => {
var {name, args, callId} = data,
cb = res => {
if (res instanceof Promise) {
res.then(result => RNMEvaluator.functionCallCompleted(callId, null, {_value: result}));
return;
}
if (res instanceof Error) {
RNMEvaluator.functionCallCompleted(callId, `Function ${name} raised an error ${res.message}:${res.stack}`, null);
} else {
RNMEvaluator.functionCallCompleted(callId, null, {_value: res});
}
}, func, err;
try {
func = eval(name);
} catch (e) {
err = e;
}
if (err) {
return RNMEvaluator.functionCallCompleted(callId, `Error finding a function ${err.message}`, null);
}
if (!func) {
return RNMEvaluator.functionCallCompleted(callId, `Function ${name} cannot be found`, null);
}
if (typeof func !== 'function') {
return RNMEvaluator.functionCallCompleted(callId, `${name} is not a function`, null);
}
try {
executor(func).apply(null, args.concat(cb))
} catch (e) {
RNMEvaluator.functionCallCompleted(callId, `Function ${name} raised an error ${e.message}:${e.stack}`, null);
}
}
// TODO: move to AppEventEmitter once App events are supported on android.
DeviceEventEmitter.addListener('RNMEvaluator.callAsyncFunction',
data => execute(data, f => f));
DeviceEventEmitter.addListener('RNMEvaluator.callSyncFunction',
data => execute(data, f => (...args) => args.pop()(f.apply(null, args))));
exports.emit = (name, res) => {
RNMEvaluator.emit(name, {_value: res});
};