-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.js
More file actions
52 lines (44 loc) · 1.42 KB
/
api.js
File metadata and controls
52 lines (44 loc) · 1.42 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
/* eslint-disable no-restricted-globals */
/* eslint-disable no-undef */
var commonFactory = require('./worker.common')
var stub = require('./stub')
module.exports = function(worker, host) {
host = host || self
var operations
host.onmessage = function(e) {
var common = commonFactory(host || self)
var emit = common.emit(e.data.id)
var emitError = common.emitError(emit)
var userEmit = common.userEmit(emit)
try {
switch(e.data.type) {
case 'init':
Promise.resolve(worker(e.data.param, userEmit))
.then(function(result) {
operations = result
emit({ result: { type: 'api', operations: Object.keys(result) } })
})
.catch(function(error) {
emitError(error)
host.close()
})
break;
case 'invoke':
if(!operations[e.data.operation])
emitError(new Error('Unknown operation: ' + e.data.operation))
Promise.resolve(operations[e.data.operation](e.data.param, userEmit))
.then(function(result) { emit({ result: result }) })
.catch(emitError)
break;
default:
emitError(new Error('Unknown internal operation: ' + e.data.type))
}
} catch(error) {
emitError(error)
host.close()
}
}
}
module.exports.stub = function(worker) {
return stub(worker, module.exports)
}