How to migrate plugins to YAKjs 3.x

Oh no, a breaking change. Sorry folks, but everything is getting better and it is easy to change your existing plugins to work with YAKjs 3.x.

Plugins are now handled like node modules, and the plugin needs to be exported.

module.exports = { ... }

Let's start with this "old" plugin.

function EchoPlugin(require, context) {
    'use strict';

    /**
     * @param {WebSocketMessage} message
     * @param {WebSocketConnection} connection
     */
    this.onMessage = function onMessage(message, connection) {
        connection.send(message.data);
    };
}

1) Export your plugin with a name and description

'use strict';

function EchoPlugin(context) {
    /**
     * @param {WebSocketMessage} message
     * @param {WebSocketConnection} connection
     */
    this.onMessage = function onMessage(message, connection) {
        connection.send(message.data);
    };
}

module.exports = {
    name: 'echo',
    description: 'Every received message will be send back'
}

2) Add the create worker function

'use strict';

function EchoPluginWorker(context) {
    /**
     * @param {WebSocketMessage} message
     * @param {WebSocketConnection} connection
     */
    this.onMessage = function onMessage(message, connection) {
        connection.send(message.data);
    };
}

module.exports = {
    name: 'echo',
    description: 'Every received message will be send back',
    createWorker: (context) => new EchoPluginWorker(context);
}

Here we also have renamed the constructor function to EchoPluginWorker, but this is up to you how you name things.

More Information:

3) Optional: Load modules

'use strict';

const myPlugin = require('../modules/myplugin');
const jsonStore = require('../common/jsonStore');

function EchoPluginWorker(context) {
    /**
     * @param {WebSocketMessage} message
     * @param {WebSocketConnection} connection
     */
    this.onMessage = function onMessage(message, connection) {
        connection.send(message.data);
    };
}

module.exports = {
    createWorker: (context) => new EchoPluginWorker(context);
}

More Information:

4) Optional: Use logger via context

The logger was moved to the context object and is no longer available via require. For example:

 'use strict';

 function EchoPluginWorker(context) {
     /**
      * @param {WebSocketMessage} message
      * @param {WebSocketConnection} connection
      */
     this.onMessage = function onMessage(message, connection) {
         context.log.info('Message received.');
         connection.send(message.data);
     };
 }

 module.exports = {
     createWorker: (context) => new EchoPluginWorker(context);
 }

More Information:

5) Optional: Use new command feature

Now your plugin can export a list of commands that can be triggered via the HTTP API or via the user interface.

More Information:

6) Finished

Now let's test your plugin.

With YAKjs 3.x you can start yakjs with an attached node debugger and debug your plugins.