UNPKG

1.36 kBtext/coffeescriptView Raw
1noflo = require 'noflo'
2{_} = require 'underscore'
3
4class Callback extends noflo.Component
5 description: 'This component calls a given callback function for each
6 IP it receives. The Callback component is typically used to connect
7 NoFlo with external Node.js code.'
8 icon: 'sign-out'
9
10 constructor: ->
11 @callback = null
12
13 # We have two input ports. One for the callback to call, and one
14 # for IPs to call it with
15 @inPorts = new noflo.InPorts
16 in:
17 description: 'Object passed as argument of the callback'
18 datatype: 'all'
19 callback:
20 description: 'Callback to invoke'
21 datatype: 'function'
22 # The optional error port is used in case of wrong setups
23 @outPorts = new noflo.OutPorts
24 error:
25 datatype: 'object'
26
27 # Set callback
28 @inPorts.callback.on 'data', (data) =>
29 unless _.isFunction data
30 @error 'The provided callback must be a function'
31 return
32 @callback = data
33
34 # Call the callback when receiving data
35 @inPorts.in.on 'data', (data) =>
36 unless @callback
37 @error 'No callback provided'
38 return
39 @callback data
40
41 error: (msg) ->
42 if @outPorts.error.isAttached()
43 @outPorts.error.send new Error msg
44 @outPorts.error.disconnect()
45 return
46 throw new Error msg
47
48exports.getComponent = -> new Callback