cylon/lib/registry.js

118 lines
2.5 KiB
JavaScript
Raw Normal View History

/*
2014-11-01 05:14:02 +08:00
* Registry
*
2014-11-01 05:14:02 +08:00
* The Registry contains references to all Drivers and Adaptors Cylon is aware
* of, along with which module they live in (e.g. cylon-firmata).
*
* cylonjs.com
*
2015-01-08 04:58:50 +08:00
* Copyright (c) 2013-2015 The Hybrid Group
* Licensed under the Apache 2.0 license.
*/
"use strict";
2014-12-16 03:15:29 +08:00
var Logger = require("./logger");
2014-11-06 06:24:07 +08:00
// Explicitly these modules here, so Browserify can grab them later
2014-12-16 03:15:29 +08:00
require("./test/loopback");
require("./test/test-adaptor");
require("./test/test-driver");
require("./test/ping");
var missingModuleError = function(module) {
2014-12-16 03:15:29 +08:00
var str = "Cannot find the '" + module + "' module.\n";
str += "This problem might be fixed by installing it with ";
str +="'npm install " + module + "' and trying again.";
2014-12-16 03:15:29 +08:00
console.log(str);
2014-12-16 03:15:29 +08:00
process.emit("SIGINT");
};
2014-11-01 05:14:02 +08:00
var Registry = module.exports = {
data: {},
register: function(module) {
if (this.data[module]) {
return this.data[module].module;
}
var pkg;
try {
pkg = require(module);
} catch (e) {
if (e.code === "MODULE_NOT_FOUND") {
missingModuleError(module);
}
throw e;
}
this.data[module] = {
module: pkg,
adaptors: pkg.adaptors || [],
2014-11-06 06:24:07 +08:00
drivers: pkg.drivers || [],
dependencies: pkg.dependencies || []
};
2014-11-06 06:24:07 +08:00
this.logRegistration(module, this.data[module]);
this.data[module].dependencies.forEach(function(dep) {
Registry.register(dep);
});
return this.data[module].module;
},
findBy: function(prop, name) {
// pluralize, if necessary
if (!/s$/.test(name)) {
prop += "s";
}
return this.search(prop, name);
},
findByModule: function(module) {
if (!this.data[module]) {
return null;
}
return this.data[module].module;
},
2014-11-06 06:24:07 +08:00
logRegistration: function(name) {
var module = this.data[name];
Logger.debug("Registering module " + name);
2014-12-16 03:15:29 +08:00
["adaptors", "drivers", "dependencies"].forEach(function(field) {
2014-11-06 06:24:07 +08:00
if (module[field].length) {
Logger.debug(" " + field + ":");
module[field].forEach(function(item) {
Logger.debug(" - " + item);
});
}
});
},
search: function(entry, value) {
for (var name in this.data) {
var repo = this.data[name];
if (~repo[entry].indexOf(value)) {
return repo.module;
}
}
return false;
}
};
// Default drivers/adaptors:
2014-12-16 03:15:29 +08:00
["loopback", "ping", "test-adaptor", "test-driver"].forEach(function(module) {
Registry.register("./test/" + module);
});