UNPKG

latte_web3

Version:
120 lines (117 loc) 3.68 kB
(function(define) {'use strict' define("latte_web/server/rpc/orpc", ["require", "exports", "module", "window"], function(require, exports, module, window) { var latte_lib = require("latte_lib"); var latte_watch = require("latte_watch"); var Modules = require("latte_require"); var defaultConfig = {}; function RPC(config) { if(latte_lib.isString(config)) { config = { path: config } }; this.config = latte_lib.merger(defaultConfig, config); this.methods = {}; this.id = 0; }; latte_lib.inherits(RPC, latte_lib.events); (function() { this.loadDir = function(path) { var self = this; var files = latte_lib.fs.readdirSync(path); files.forEach(function(filename) { var stat = latte_lib.fs.statSync(path + "/" + filename); if(stat.isFile()) { self.loadFile(path + "/"+ filename); }else if(stat.isDirectory()){ self.loadDir(path + "/" + filename); } }); } this.reload = function(path) { var self = this; this.config.path = path = path || this.config.path; if(!path) { return; } this.rpcRequire = null; this.rpcRequire = Modules.create("./"); //this.load(path); if(this.watcher) { this.watcher.close(); this.watcher = null; } this.watcher = latte_watch.create(path); this.watcher.on("addDir", function(addDirName ) { self.loadDir(addDirName); }); this.watcher.on("unlink" , function() { self.reload(); }); this.watcher.on("unlinkDir", function(){ self.reload(); }); this.watcher.on("add", function(filename) { self.loadFile(filename); }); this.watcher.on("change", function() { self.reload(); }); this.loadDir(path); } this.Call = function(method, params, socket, cb) { var self = this; if(latte_lib.isFunction(socket)) { cb = socket; socket = null; } this.write({ method: method, params: params, id: ++self.id }, socket); if(cb) { this.once(self.id, cb); } } this.Set = function(method, func) { this.methods[method] = func; } var backData = function(err, result, id) { return { error: err, result : result, id: id }; } this.addWorker = function(worker) { var self = this; worker.process.on("message", function(data, socket) { if(socket) { socket.readable = socket.writeable = true; socket.resume(); } if(data.method) { var method = self.methods[data.method]; if(method) { if(!latte_lib.isArray(data.params)) { data.params = [].concat(data.params); } socket && data.params.push(socket); data.params.push(function(err, result, s) { worker.send(backData(err, result, data.id), s); }); try { method.apply(worker, data.params); }catch(e) { self.emit("error", e); } } }else if(data.id) { self.emit(data.id, data.error, data.result, socket); } }); } }).call(RPC.prototype); module.exports = RPC; }); })(typeof define === "function"? define: function(name, reqs, factory) {factory(require, exports, module); });