Skip to content

Plugin Architecture

Thiemo edited this page Mar 30, 2018 · 6 revisions

UnicornLogger Plugin Architecture

Work in progress

Summary

As a plugin/middleware developer you

  • have to write a plugin that can be instantiated (new MyPlugin)
  • you can optionally expose initalize() and call() methods, basically implement the UnicornLoggerMiddleware interface
    • initalize(donkeycorn: UnicornLoggerInstanceOrMutator) gives you the option to register new methods
    • call(methodName: string, logger: UnicornLogger, next: (args: Array<*>) => void, args: Array<*>)

UnicornLoggerInstanceOrMutator

  • registerMethod(methodName: string)
  • use(middleware: UnicornLoggerMiddleware)

UnicornLoggerInstance

  • namespace: string

UnicornLoggerMiddleware

interface UnicornLoggerMiddleware {
	/**
	 * Initialization method called on adding the middleware.
	 * Call `logger.registerMethod(string)` to add new methods to the instance or class
	 *
	 * @public
	 * @method initialize
	 * @param {UnicornLogger | Class<UnicornLogger>} Reference to the logger instance or class, allows to register new methods
	 * @returns {void}
	 * @example
	 *
	 * initialize(logger) {
	 *   logger.registerMethod('foo');
	 * }
	 *
	 */
	initialize?: (logger: UnicornLogger | Class<UnicornLogger>) => void;

	/**
	 * Called whenever a logging function of UnicornLogger is called.
	 * Middlewares can implement this to react to function calls
	 *
	 * @public
	 * @method call
	 * @param {string} methodName Name of the method being called
         * @param {UnicornLogger} logger The instance of UnicornLogger the method was called on
	 * @param {function(args)} next Next function used to call the nex middleware,
	 * use this with the members of args as params.
	 * You can also choose to cancel the call by not calling next, this will also
	 * stop the application of other remaining middlewares.
	 * @param {...Array} args Arguments of the call
	 * @returns {void}
	 * @example
	 *
	 * call(method, logger, next, args) {
	 *   if (method === 'fn') {
	 *     this.fn(logger.namespace, ...args);
	 *   }
	 *   next(...args);
	 * }
	 */
	call?: (methodName: string, logger: UnicornLogger, next: (...args: Array<*>) => void, args: Array<*>) => void;
}

Example Middleware

class ExamplePlugin {
	setup(logger) {
		logger.registerMethod('sample');      
	}

	log(namespace, args) {
		console.log(namespace, 'example', ...args);
	}

	call(method, logger, next, ...args) {
		if (method === 'sample') {
			this.log(logger.namespace, args);
			return next('Sampled!', ...args);
		}
		return next();
	}
}