0.0.2 • Published 2 years ago

@binsoul/node-red-bundle-processing v0.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

node-red-bundle-processing

Software License

Provides a handler for Node-RED "input" events which reads inputs and writes outputs for action objects generated by a factory.

Example

import { Action, ActionFactory, Input, InputDefinition, Message, MessageHandler, Output, OutputDefinition } from '@binsoul/node-red-bundle-processing';
import { NodeDef } from '@node-red/registry';
import type { Node, NodeInitializer } from 'node-red';

/**
 * Reads a string from msg.payload and writes a modified string to msg.payload.
 */
class HelloWorld implements Action {
    defineInput(): InputDefinition {
        const definition = new InputDefinition();

        definition.set('actionInput', {
            source: 'msg',
            property: 'payload',
            type: 'string',
            required: true,
        });

        return definition;
    }

    defineOutput(): OutputDefinition {
        const definition = new OutputDefinition();

        definition.set('actionOutput', {
            target: 'msg',
            property: 'payload',
            type: 'string',
            channel: 0,
        });

        return definition;
    }

    execute(input: Input): Output {
        const output = new Output();

        const actionInput = input.getRequiredValue<string>('actionInput');
        output.setValue('actionOutput', `Hello ${actionInput}!`);

        return output;
    }
}

/**
 * Return a HelloWorld action if there is a msg.payload.
 */
class Factory implements ActionFactory {
    build(message: Message): Action | Array<Action> | null {
        if (typeof message.data.payload !== 'undefined') {
            return new HelloWorld();
        }

        return null;
    }
}

/**
 * Registers a node named "hello-world".
 */
const nodeInitializer: NodeInitializer = (RED): void => {
    function NodeConstructor(this: Node, userConfiguration: NodeDef): void {
        RED.nodes.createNode(this, userConfiguration);

        const actionFactory = new Factory();
        const messageHandler = new MessageHandler(RED, this, actionFactory);

        this.on('input', (msg, send, done) => messageHandler.handle(msg, send, done));
    }

    RED.nodes.registerType('hello-world', NodeConstructor);
};

export = nodeInitializer;

Dependencies

The bundle is tested with Node.js v18 and Node-RED v3.

License

The MIT License (MIT). Please see License File for more information.