FlowStream
The Flow module, FlowStream instances, component definitions, component instances and messages.
On this page
FlowStreams are graphs of components loaded from .flow files in /flowstreams/ or with Flow.load(). This page lists the Flow object, the FlowStream instance, the component definition (exports), the component instance and the message ($). The guide FlowStream explains how to use them with examples; this page is the exact reference.
API
config
CONF.directory_flowstreams = '/flowstreams/'
The directory with .flow files that are loaded when the app starts.
CONF.directory_flowstreams = '/flowstreams/'Every file with the .flow extension in this directory is read as JSON and passed to Flow.load() when the app starts. Files whose name contains -bk or _bk are skipped, so you can keep backups next to them. The directory plugins/{name}/flowstreams/ of each plugin is loaded the same way.
In debug mode the watcher restarts the app when a .flow file changes. The default is /flowstreams/; an empty value turns the loading off.
flowstreams/
orders.flow
orders_bk.flow // skipped
plugins/
crm/
flowstreams/
leads.flow
config
{ id, name, components, design, variables, worker, ... }
The JSON object stored in a .flow file and passed to Flow.load().
{ id, name, components, design, variables, worker, ... }id{String}: the identifier, the key inFlow.instances. A random one is generated when it is missing.name{String}: a readable name (default: theid).components{Object}: component id → the component as an HTML string with a<script total>block.design{Object}: instance id →{ component, config, connections, x, y }.connectionsmaps an output id to an array of{ id: 'instanceid', index: 'inputid' }.variables{Object}: values that components read withinstance.replace()or$.variables().worker{String/Boolean}:'worker'runs the FlowStream in a worker thread, another truthy value (for example'fork') in a child process;false(default) in the main process.memory{Number}: the heap limit in MB for a child process (--max-old-space-size).cloning{Boolean}: clones the message data for every connection (defaulttrue).paused{Boolean}: starts the FlowStream paused.readonly{Boolean}: nosaveevents are emitted.origin{String}: the public URL of the app, used byinstance.href()and the{hostname}variable.
flowstream.export() returns the same shape, so you can write it back to the .flow file.
{
"id": "orders",
"name": "Orders",
"components": {
"uppercase": "<script total>...</script>",
"print": "<script total>...</script>"
},
"design": {
"a1": { "component": "uppercase", "config": { "field": "name" }, "connections": { "output": [{ "id": "b1", "index": "input" }] } },
"b1": { "component": "print", "config": {} }
},
"variables": { "currency": "EUR" }
}
method
Flow.load(schema, [callback])
Loads a FlowStream from its schema and starts it.
Flow.load(schema, [callback])| Parameter | Type | Description |
|---|---|---|
schema |
Object |
The FlowStream schema (the content of a .flow file). |
callback? |
Function |
function(err, instance); instance is the FlowStream instance. |
Creates the FlowStream, registers its components, creates the instances of the design and calls callback when everything is ready. The instance is stored in Flow.instances[schema.id] and the schema in Flow.db[schema.id].
When a FlowStream with the same id is already loaded, it is updated with the new schema instead (components, design and variables are replaced) and the callback gets the existing instance.
A schema without name, components, design, sources or variables gets empty defaults, so an empty flow loads.
// definitions/flowstream.js
ON('ready', function() {
var schema = {};
schema.id = 'orders';
schema.name = 'Orders';
schema.components = {};
schema.components.uppercase = F.Fs.readFileSync(PATH.root('components/uppercase.html'), 'utf8');
schema.components.print = F.Fs.readFileSync(PATH.root('components/print.html'), 'utf8');
schema.design = {};
schema.design.a1 = { component: 'uppercase', config: { field: 'name' }, connections: { output: [{ id: 'b1', index: 'input' }] } };
schema.design.b1 = { component: 'print', config: {} };
Flow.load(schema, function(err, instance) {
instance.send('a1', { name: 'Peter' });
});
});
method
Flow.init([directory], [callback])
Loads all .flow files of a directory.
Flow.init([directory], [callback])| Parameter | Type | Description |
|---|---|---|
directory? |
String |
An absolute path. Default: PATH.root('flowstreams') |
callback? |
Function |
Called when all files are loaded. |
Reads every .flow file of directory (default flowstreams/ in the app root), skips names with -bk or _bk and loads each one with Flow.load(). A missing directory is not an error. The framework calls it for /flowstreams/ at startup; call it yourself for another directory.
Flow.init(PATH.root('databases/flows'), function() {
console.log(Object.keys(Flow.instances));
});
property
Flow.instances
The loaded FlowStream instances by their id.
Flow.instancesReturns Object
An object where each key is the id of a schema and each value is the FlowStream instance returned by Flow.load(). Use it to send data to a FlowStream from routes, schemas or jobs.
exports.install = function() {
ROUTE('POST /api/orders/', create);
};
function create() {
var self = this;
var flow = Flow.instances.orders;
if (!flow) {
self.invalid(404);
return;
}
flow.send('a1', self.body, function(err, response) {
if (err)
self.invalid(err);
else
self.json(response.data);
});
}
property
Flow.db
The schemas of the loaded FlowStreams by their id.
Flow.dbReturns Object
Holds the schema passed to Flow.load(); it is replaced by the exported schema each time the FlowStream saves itself (see Flow.on('save')).
method
Flow.remove(id)
Destroys a FlowStream and removes it from Flow.instances and Flow.db.
Flow.remove(id)| Parameter | Type | Description |
|---|---|---|
id |
String |
The FlowStream id. |
Stops all instances, closes a worker, removes the FlowStream and emits remove with its schema. The .flow file is not deleted.
Flow.remove('orders');
method
Flow.reload(schema)
Updates a loaded FlowStream with a new schema.
Flow.reload(schema)| Parameter | Type | Description |
|---|---|---|
schema |
Object |
The new schema; id selects the FlowStream. |
Returns Boolean true when the FlowStream exists.
Finds the FlowStream by schema.id, stores the schema in Flow.db and rewrites the running FlowStream with it (components, design and variables). Returns false when no FlowStream with this id is loaded. Flow.load() calls it for an id that is already loaded.
method
Flow.socket(id, websocket, [check])
Connects a WebSocket controller to a FlowStream for the Flow designer.
Flow.socket(id, websocket, [check])| Parameter | Type | Description |
|---|---|---|
id |
String |
The FlowStream id (or the FlowStream itself). |
websocket |
WebSocket |
The WebSocket controller (this in a SOCKET route). |
check? |
Function |
function(client, next); call next() to let the client in. |
The designer talks to the FlowStream through this WebSocket: it reads components, the design and the stats, and sends changes back. check(client, next) runs for each new client; call next() to accept it. The socket is detached when the WebSocket controller is destroyed. An unknown id destroys the socket.
exports.install = function() {
ROUTE('+SOCKET /flowstreams/{id}/', designer);
};
function designer(id) {
var self = this;
Flow.socket(id, self, function(client, next) {
if (client.user && client.user.sa)
next();
else
client.close();
});
}
delegate
Flow.onerror = function(err, source, id, componentid, stack) {}
Handles errors of all FlowStreams.
Flow.onerror = function(err, source, id, componentid, stack) {}| Parameter | Type | Description |
|---|---|---|
err |
Error/String |
The error. |
source |
String |
Where it happened, for example instance_message or instance_make. |
id |
String |
The instance id. |
componentid |
String |
The component id. |
stack? |
String |
The stack, for FlowStreams in a worker. |
The default prints a block with the FlowStream name, the source, the instance id and the component id to the console. Assign your own function before the FlowStreams are loaded; this is the FlowStream instance (this.id is its id).
Flow.onerror = function(err, source, id, componentid) {
console.error('FlowStream', this.id, source, id, componentid, err);
};
event
Flow.on('load', function(instance, schema) {})
A FlowStream was loaded and is ready.
Flow.on('load', function(instance, schema) {})| Parameter | Type | Description |
|---|---|---|
instance |
Object |
The FlowStream instance. |
schema |
Object |
The schema. |
Emitted after Flow.load() finished, before its callback.
Flow.on('load', function(instance, schema) {
console.log('FlowStream ready:', schema.name);
});
event
Flow.on('save', function(schema) {})
A FlowStream changed and its schema should be stored.
Flow.on('save', function(schema) {})| Parameter | Type | Description |
|---|---|---|
schema |
Object |
The exported schema with id, components, design, variables and the other fields. |
Emitted about five seconds after the last change: an edit in the designer, flowstream.variables(), flowstream.reconfigure() or instance.save(). The framework does not write .flow files itself; store the schema here. Nothing is emitted for a schema with readonly: true.
Flow.on('save', function(schema) {
delete schema.unixsocket;
F.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\t'), NOOP);
});
method
FLOWSTREAM([name], [errorhandler])
Creates or returns a FlowStream engine by name, without workers or the designer.
FLOWSTREAM([name], [errorhandler])| Parameter | Type | Description |
|---|---|---|
name? |
String |
The engine name. Default: 'default' |
errorhandler? |
Function |
function(err, source, instance). Default: console.error |
Returns FlowStream The engine.
Returns the engine that runs components and messages. The same name returns the same engine (default name default). It has no .flow file, no worker and no saving; Flow.load() builds on it. Main methods:
add(id, html, [callback])registers a component from its HTML.use(design, [callback])creates instances from a design object (returns a Promise without callback);insert(design, [callback])adds instances;remove(keys, [callback])removes them.trigger('instanceid__inputid', data)sends data to an input;send('instanceid__outputid', data)sends data from an output.find(id)returns an instance;pause(is);reconfigure(id, config);destroy().- Events:
message,end,connect,disconnect,configure,schema.
var flow = FLOWSTREAM('local');
var print = '<script total>exports.inputs = [{ id: \'input\', name: \'Input\' }]; exports.make = function(instance) { instance.message = function($) { console.log($.data); $.destroy(); }; };</script>';
flow.add('print', print, function() {
flow.use({ p1: { component: 'print', config: {} } }, function() {
flow.trigger('p1__input', { hello: 'world' });
});
});
method
flowstream.send(path, data, [callback])
Sends data to one instance and waits for the end of the message.
flowstream.send(path, data, [callback])| Parameter | Type | Description |
|---|---|---|
path |
String |
The target instance. |
data |
Object |
The message data. |
callback? |
Function |
function(err, response). |
path is an instance id, @componentid (the first instance of the component) or #name (the first instance whose component has this name). Add /inputid to set $.input. The data goes to instance.message of the target, so it must define instance.message.
The callback runs when the message and all its copies are destroyed. It gets { error, repo, data, count, cloned, duration, meta: { id, component } }, where data is the data of the last message. An unknown target calls callback(404).
Flow.instances.orders.send('a1', { name: 'Peter' }, function(err, response) {
console.log(response.data, response.duration + ' ms');
});
method
flowstream.exec(opt, [callback])
Sends a message to one or more instances with a repository, variables and a timeout.
flowstream.exec(opt, [callback])| Parameter | Type | Description |
|---|---|---|
opt |
Object |
Options. |
callback? |
Function |
function(err, response); response has uid, ref, error, repo, data, count, cloned, duration, meta. |
opt.id is an instance id, @componentid (all instances of the component) or #name (all instances with the component name). Each target must define instance.message. The callback runs for each target when its message ends; an unknown target gives 404.
opt.data{Object}: the data (default{}).opt.repo{Object}: the initial$.repo.opt.vars{Object}: the initial$.vars.opt.timeout{Number}: ms; then the message ends witherror408.opt.uid,opt.ref: returned back in the response.
Flow.instances.orders.exec({ id: '@uppercase', data: { name: 'Peter' }, timeout: 5000 }, function(err, response) {
if (err === 408)
console.log('Timeout');
});
method
flowstream.trigger(id, data)
Calls the instance.trigger handler of instances.
flowstream.trigger(id, data)| Parameter | Type | Description |
|---|---|---|
id |
String |
The target. |
data? |
Object |
Passed to instance.trigger(data). |
Returns FlowStreamInstance The instance.
id is an instance id, @componentid (all instances of the component) or #name. Only instances that define instance.trigger are called; nothing happens while the FlowStream is paused.
Flow.instances.orders.trigger('@timer', { manual: true });
method
flowstream.pause([is])
Pauses or resumes the FlowStream.
flowstream.pause([is])| Parameter | Type | Description |
|---|---|---|
is? |
Boolean |
true pauses, false resumes. |
Returns FlowStreamInstance The instance.
A paused FlowStream drops new messages and calls instance.pause(is) of each instance that defines it. Without an argument it toggles the state.
Flow.instances.orders.pause(true);
method
flowstream.reconfigure(id, config)
Changes the configuration of one instance.
flowstream.reconfigure(id, config)| Parameter | Type | Description |
|---|---|---|
id |
String |
The instance id. |
config |
Object |
The keys to change. |
Returns FlowStreamInstance The instance.
The keys of config are merged into the instance configuration, then instance.configure(config) is called and the FlowStream saves itself.
Flow.instances.orders.reconfigure('a1', { field: 'email' });
method
flowstream.variables(variables)
Replaces the variables of the FlowStream.
flowstream.variables(variables)| Parameter | Type | Description |
|---|---|---|
variables |
Object |
The new variables. |
Returns FlowStreamInstance The instance.
Calls instance.variables(variables) and instance.vary('variables') of each instance that defines them and saves the FlowStream.
Flow.instances.orders.variables({ currency: 'USD', api: 'https://api.example.com' });
method
flowstream.components(callback)
Reads the registered components.
flowstream.components(callback)| Parameter | Type | Description |
|---|---|---|
callback |
Function |
function(err, components). |
Returns FlowStreamInstance The instance.
The callback gets an array with id, name, type, icon, color, group, version, author, config, inputs, outputs, readme, html, css, js and settings of each component.
Flow.instances.orders.components(function(err, components) {
console.log(components.map(c => c.name));
});
method
flowstream.add(id, html, [callback])
Registers or replaces a component at runtime.
flowstream.add(id, html, [callback])| Parameter | Type | Description |
|---|---|---|
id |
String |
The component id. |
html |
String |
The component source. |
callback? |
Function |
function(err). |
Returns FlowStreamInstance The instance.
html is the component file with a <script total> block. Existing instances of the component are created again with the new code. Use flowstream.rem(id, [callback]) to unregister a component and remove its instances.
var html = F.Fs.readFileSync(PATH.root('components/uppercase.html'), 'utf8');
Flow.instances.orders.add('uppercase', html, function(err) {
err && console.error(err);
});
method
flowstream.export(callback)
Exports the current schema of the FlowStream.
flowstream.export(callback)| Parameter | Type | Description |
|---|---|---|
callback |
Function |
function(err, schema). |
Returns FlowStreamInstance The instance.
The callback gets the schema in the .flow format: components (raw HTML), design, variables, sources, paused and the other fields of the loaded schema.
Flow.instances.orders.export(function(err, schema) {
F.Fs.writeFile(PATH.root('flowstreams/orders_bk.flow'), JSON.stringify(schema), NOOP);
});
property
flowstream.stats
since 0.0.96
Statistics of the FlowStream.
flowstream.statsReturns Object
Contains messages (messages sent), pending (messages in progress), minutes (minutes running), mm (messages in the last minute), errors (count of the last errors, at most 10), memory and paused. memory (heap in bytes) is measured only in a worker or child process. For a FlowStream in a worker the object comes from the worker about every 15 seconds and also contains pid; before the first report it is undefined.
var stats = Flow.instances.orders.stats;
console.log(stats.messages, stats.pending);
method
flowstream.remove()
Destroys this FlowStream and removes it from Flow.
flowstream.remove()The same as Flow.remove(flowstream.id). flowstream.destroy() only stops the FlowStream and its worker; it stays in Flow.instances.
Flow.instances.orders.remove();
method
exports.make = function(instance, config) {}
Creates one instance of the component.
exports.make = function(instance, config) {}| Parameter | Type | Description |
|---|---|---|
instance |
Object |
The new instance. |
config |
Object |
The instance configuration. |
A component is an HTML file whose <script total> block is the server code; exports is the component. make runs for each instance of the design, with this and instance both the instance and config its configuration (exports.config merged with the design config). Assign handlers such as instance.message here.
The other blocks of the file are for the designer: <readme>, <settings>, <style>, <script> (client code), <body> and <template>.
<script total>
exports.name = 'Uppercase';
exports.icon = 'ti ti-font';
exports.config = { field: 'name' };
exports.inputs = [{ id: 'input', name: 'Input' }];
exports.outputs = [{ id: 'output', name: 'Output' }];
exports.make = function(instance, config) {
instance.message = function($) {
var data = $.data;
if (data && typeof(data[config.field]) === 'string')
data[config.field] = data[config.field].toUpperCase();
$.send('output', data);
};
};
</script>
<readme>
Converts one field of the incoming object to upper case.
</readme>
property
exports.inputs = [{ id: 'input', name: 'Input' }]
The inputs and outputs of the component.
exports.inputs = [{ id: 'input', name: 'Input' }]Returns Array
exports.inputs and exports.outputs are arrays of { id, name }. Connections in the design refer to these ids: connections: { outputid: [{ id: 'instanceid', index: 'inputid' }] }. A connection to an input that the target component does not declare is removed. A component without inputs only sends (for example a timer); one without outputs ends the messages.
exports.inputs = [{ id: 'input', name: 'Input' }];
exports.outputs = [{ id: 'ok', name: 'Valid' }, { id: 'error', name: 'Invalid' }];
property
exports.config = {}
The default configuration of each instance.
exports.config = {}Returns Object
A copy is merged with the config of the instance in the design and passed to exports.make() as config.
exports.config = { field: 'name', timeout: 5000 };
property
exports.name = 'Uppercase'
The name and the other metadata of the component.
exports.name = 'Uppercase'Returns String
Metadata for the designer and for flowstream.components(): exports.name, exports.icon, exports.color, exports.group, exports.type, exports.version, exports.author and exports.meta. The #name selector of send(), exec() and trigger() matches exports.name. The component id is the key in the components object of the schema.
exports.name = 'Uppercase';
exports.icon = 'ti ti-font';
exports.color = '#5D9CEC';
exports.group = 'Text';
exports.version = '1';
exports.author = 'Total.js';
property
exports.npm = ['package']
NPM packages that the component needs.
exports.npm = ['package']Returns Array
The packages are installed with NPMINSTALL() before the component is registered.
exports.npm = ['qrcode'];
exports.make = function(instance) {
instance.message = function($) {
var QR = require('qrcode');
QR.toDataURL($.data.text, function(err, url) {
$.send('output', url);
});
};
};
delegate
instance.message = function($) {}
Receives the messages that arrive at the inputs.
instance.message = function($) {}| Parameter | Type | Description |
|---|---|---|
$ |
Message |
The message. |
$ is the message; $.input is the id of the input. Instead of one handler you can define instance.message_INPUTID for one input. A message that no handler takes is destroyed. Each message must end: send it on with $.send() or call $.destroy().
exports.make = function(instance) {
instance.message_a = function($) {
$.send('output', { from: 'A', data: $.data });
};
instance.message_b = function($) {
$.destroy();
};
};
method
instance.send(output, data, [controller])
Sends data from an output of the instance.
instance.send(output, data, [controller])| Parameter | Type | Description |
|---|---|---|
output |
String |
The output id. |
data |
Object |
The data or a message. |
controller? |
Controller |
Makes $.user, $.body and the other request properties available. |
Returns Number Count of sent messages.
Creates a new message for each connection of output. When data is a message, its copies keep the repository and the callbacks of that message. Returns the number of messages sent (0 when the output has no connection or the FlowStream is paused).
exports.outputs = [{ id: 'output', name: 'Tick' }];
exports.make = function(instance, config) {
var timer = setInterval(function() {
instance.send('output', { ts: new Date() });
}, config.interval || 5000);
instance.close = function() {
clearInterval(timer);
};
};
method
instance.newmessage([data])
Creates a new message owned by this instance.
instance.newmessage([data])| Parameter | Type | Description |
|---|---|---|
data? |
Object |
The data. |
Returns Message The message.
Send it with $.send(output). Unlike instance.send(), you can add listeners and a repository before sending.
var msg = instance.newmessage({ id: 1 });
msg.repo.started = Date.now();
msg.on('end', function(msg) {
instance.status('Last run: ' + (Date.now() - msg.repo.started) + ' ms');
});
msg.send('output');
method
instance.status(data, [delay])
Shows a status of the instance in the designer.
instance.status(data, [delay])| Parameter | Type | Description |
|---|---|---|
data |
Object/String |
The status. |
delay? |
Number |
Delay in ms. |
data is any value that the component design (<body>, <script>) can render. With delay (ms) the status is sent once after this time, which avoids flooding the designer. Without arguments the last status is sent again.
var count = 0;
instance.message = function($) {
count++;
instance.status({ count: count }, 1000);
$.send('output');
};
method
instance.dashboard(data)
Sends data to the dashboard of the designer.
instance.dashboard(data)| Parameter | Type | Description |
|---|---|---|
data |
Object |
Dashboard data. |
Like instance.status(), but for dashboard widgets. The last value is kept and sent again when called without arguments.
instance.dashboard({ temperature: 21.5 });
method
instance.throw(err)
Reports an error of the instance.
instance.throw(err)| Parameter | Type | Description |
|---|---|---|
err |
Error/String |
The error. |
The error is stored in the last ten errors of the FlowStream (counted in stats.errors), shown in the designer and passed to Flow.onerror. $.throw(err) does the same and also sets $.error. Neither ends the message.
instance.message = function($) {
if (!$.data.email) {
$.throw('Missing email');
$.destroy();
return;
}
$.send('output');
};
property
instance.config
The configuration of the instance.
instance.configReturns Object
The default exports.config merged with the config of the design. A change from the designer or flowstream.reconfigure() updates the same object and calls instance.configure(config).
var field = instance.config.field;
delegate
instance.configure = function(config) {}
Runs when the configuration of the instance changes.
instance.configure = function(config) {}| Parameter | Type | Description |
|---|---|---|
config |
Object |
The new configuration. |
Called after the designer, a new design or flowstream.reconfigure() changed instance.config. Not called for the first configuration; use exports.make() for that.
var timer;
instance.configure = function(config) {
timer && clearInterval(timer);
timer = setInterval(() => instance.send('output', {}), config.interval || 5000);
};
instance.configure(instance.config);
delegate
instance.close = function(removed) {}
Runs when the instance stops.
instance.close = function(removed) {}| Parameter | Type | Description |
|---|---|---|
removed? |
Boolean |
true when the instance is removed, not only re-created. |
Called when the instance is removed from the design, its component is replaced or removed, or the FlowStream is unloaded. Clear timers and close connections here. Other optional handlers: instance.init() (once, after the design is created), instance.refresh() (after each design change), instance.pause(is) and instance.variables(variables).
instance.close = function() {
clearInterval(timer);
};
delegate
instance.trigger = function(data) {}
Runs when the instance is triggered.
instance.trigger = function(data) {}| Parameter | Type | Description |
|---|---|---|
data? |
Object |
The trigger data. |
Called by flowstream.trigger() and by the trigger button of the designer. Typically it starts a new message.
instance.trigger = function() {
instance.send('output', { ts: new Date() });
};
method
instance.replace(str, [data], [encoding])
Replaces {key} placeholders with variables.
instance.replace(str, [data], [encoding])| Parameter | Type | Description |
|---|---|---|
str |
String/Object |
The text. |
data? |
Object |
Additional values. |
encoding? |
String/Function |
How to encode each value. |
Returns String The text with values.
Each {key} (or {{key}}) is looked up in the FlowStream variables, then variables2, then the secrets, then {hostname}, then in data (nested keys such as {user.name} work). Unknown keys stay as they are. encoding is 'url', 'json', 'querify' or function(value, key). An object as str replaces all its string values.
var url = instance.replace('{api}/orders/{id}/', { id: 15 }, 'url');
method
instance.save()
Saves changes of the instance and redraws it in the designer.
instance.save()Use it after you change instance.config or other design properties in code. The FlowStream then emits save.
instance.config.last = Date.now();
instance.save();
property
instance.main
The FlowStream engine that runs the instance.
instance.mainReturns FlowStream
Useful properties: instance.main.variables (the variables), instance.main.paused, instance.main.stats and instance.main.id. instance.instances holds all instances of the design and instance.components all registered components. instance.id is the instance id, instance.component the component id and instance.module the component.
var currency = instance.main.variables.currency;
property
$.data
The data of the message.
$.dataReturns Object
Any value. Each connection gets its own copy of objects and Buffers when cloning is on (the default). The request properties $.user, $.body, $.query, $.params, $.headers, $.ip and $.files exist only when the message was started with a controller.
instance.message = function($) {
$.data.total = $.data.price * $.data.count;
$.send('output');
};
method
$.send([output], [data], [clone])
Sends the message on from an output of the current instance.
$.send([output], [data], [clone])| Parameter | Type | Description |
|---|---|---|
output? |
String |
The output id. |
data? |
Object |
New data. |
clone? |
Boolean |
Clones the data for each connection. Default: cloning |
Returns Number Count of sent messages.
Without output it is sent from all outputs. Without data it keeps its data. When nothing is connected to the output, the message is destroyed. clone overrides the cloning option of the FlowStream for this call. Returns the number of sent messages.
instance.message = function($) {
$.send($.data.valid ? 'ok' : 'error');
};
method
$.destroy()
Ends the message.
$.destroy()Call it in the last component of a chain. When the last copy of a message ends, end is emitted and the callback of flowstream.send() or flowstream.exec() runs. $.end() is an alias.
instance.message = function($) {
console.log($.data);
$.destroy();
};
property
$.repo
An object shared by the message and all its copies.
$.repoReturns Object
Use it to pass values along the whole chain without changing $.data. It is returned as repo to the callback of flowstream.send() and flowstream.exec(). $.vars is another shared object.
// first component
$.repo.started = Date.now();
$.send('output');
// last component
$.data.duration = Date.now() - $.repo.started;
$.destroy();
method
$.variables(str, [data], [encoding])
Replaces {key} placeholders with variables and message values.
$.variables(str, [data], [encoding])| Parameter | Type | Description |
|---|---|---|
str |
String/Object |
The text. |
data? |
Object |
Values. Default: the message |
encoding? |
String/Function |
url, json, querify or a function. |
Returns String
The same as instance.replace(), but without data the message itself is used, so {data.id} reads $.data.id. $.replace() is an alias.
var url = $.variables('{api}/users/{data.id}/', null, 'url');
method
$.on(name, callback)
Listens to events of the message.
$.on(name, callback)| Parameter | Type | Description |
|---|---|---|
name |
String |
The event. |
callback |
Function |
function(msg). |
Returns Message The message.
Events: end (the last copy ended), destroy (same moment), terminate (any copy ended), message (a copy reached an instance), timeout. The listeners are shared by all copies. $.once() and $.off() exist too.
var msg = instance.newmessage(data);
msg.on('end', function(msg) {
console.log('Done', msg.data);
});
msg.send('output');
method
$.timeout([callback], time)
Limits how long each next step of the message may take.
$.timeout([callback], time)| Parameter | Type | Description |
|---|---|---|
callback? |
Function |
function(msg). |
time |
Number |
Milliseconds. |
Returns Message The message.
Every copy sent after this call ends with $.error = 408 when it is not processed within time ms; callback is called with that copy. $.totaltimeout([callback], time) limits the whole chain instead.
$.totaltimeout(function(msg) {
instance.throw('Timeout');
}, 5000);
$.send('output');