New Plugin API

- Homebridge calls single exported initializer function and passes an
API object
  - No more require() for HAP classes (doesn't play well with plugin
structure)
This commit is contained in:
Nick Farina
2015-10-18 22:20:06 -07:00
parent a3c0df1c7c
commit 27b39cbfa0
8 changed files with 155 additions and 102 deletions

View File

@@ -1,4 +1,5 @@
var chalk = require('chalk');
var util = require('util');
'use strict';
@@ -22,43 +23,66 @@ var loggerCache = {};
* Logger class
*/
function Logger(pluginName) {
this.pluginName = pluginName;
function Logger(prefix) {
this.prefix = prefix;
}
Logger.prototype.debug = function(msg) {
if (DEBUG_ENABLED)
this.log('debug', msg);
this.log.apply(this, ['debug'].concat(Array.prototype.slice.call(arguments)));
}
Logger.prototype.info = function(msg) {
this.log('info', msg);
this.log.apply(this, ['info'].concat(Array.prototype.slice.call(arguments)));
}
Logger.prototype.warn = function(msg) {
this.log('warn', msg);
this.log.apply(this, ['warn'].concat(Array.prototype.slice.call(arguments)));
}
Logger.prototype.error = function(msg) {
this.log('error', msg);
this.log.apply(this, ['error'].concat(Array.prototype.slice.call(arguments)));
}
Logger.prototype.log = function(level, msg) {
if (level == 'debug')
msg = util.format.apply(util, Array.prototype.slice.call(arguments, 1));
func = console.log;
if (level == 'debug') {
msg = chalk.gray(msg);
else if (level == 'warn')
}
else if (level == 'warn') {
msg = chalk.yellow(msg);
else if (level == 'error')
func = console.error;
}
else if (level == 'error') {
msg = chalk.bold.red(msg);
func = console.error;
}
// prepend plugin name if applicable
if (this.pluginName)
msg = chalk.cyan("[" + this.pluginName + "]") + " " + msg;
console.log(msg);
// prepend prefix if applicable
if (this.prefix)
msg = chalk.cyan("[" + this.prefix + "]") + " " + msg;
func(msg);
}
Logger.forPlugin = function(pluginName) {
return loggerCache[pluginName] || (loggerCache[pluginName] = new Logger(pluginName));
Logger.withPrefix = function(prefix) {
if (!loggerCache[prefix]) {
// create a class-like logger thing that acts as a function as well
// as an instance of Logger.
var logger = new Logger(prefix);
var log = logger.info.bind(logger);
log.debug = logger.debug;
log.info = logger.info;
log.warn = logger.warn;
log.error = logger.error;
log.log = logger.log;
log.prefix = logger.prefix;
loggerCache[prefix] = log;
}
return loggerCache[prefix];
}