Commit 7286040b authored by zhangdawei's avatar zhangdawei
Browse files

代码更加可读以及规范

parent 70e7f672
Showing with 74 additions and 64 deletions
+74 -64
'use strict';
const socketio = require('socket.io-client');
const logger = require('logl').getLogger('socketio');
const EventEmitter = require('events').EventEmitter;
const util = require('util');
const _ = require('lodash');
......@@ -10,7 +11,7 @@ module.exports = socketCon;
function socketCon(options){
if(!(this instanceof socketCon)) return new socketCon(options);
EventEmitter.call(this)
EventEmitter.call(this);
let defaultOptions = {
hostname: '127.0.0.1',
port: 9507,
......@@ -22,7 +23,7 @@ function socketCon(options){
transports: ['websocket'],
autoConnect: true,
path: '/service/config/v1.0'
}
};
_.assign(defaultOptions, options);
this.path = defaultOptions.path;
this.connected = false;
......@@ -30,62 +31,60 @@ function socketCon(options){
this.port = defaultOptions.port;
this.options = defaultOptions;
this.secret = defaultOptions.secret;
}
};
util.inherits(socketCon, EventEmitter);
socketCon.prototype.connect = function() {
const self = this;
return new Promise(function(reslove, reject) {
if(self.connected && self._socket) {
return reslove(self._socket)
return reslove(self._socket);
}
self.connectUrl = 'http://' + self.hostname + ':' + self.port + '/?secret=' +
tools.encrypt(self.secret, self.options.key, self.options.iv) + '&uuid=' + self.options.uuid;
const socketOptions = _.pick(self.options,[
'reconnection',
'reconnectionAttempts',
'hostname',
'port',
'reconnectionDelay',
'reconnectionDelayMax',
'timeout',
'autoConnect',
'transports',
'path'
]);
const _con = socketio(self.connectUrl, socketOptions);
_con.on('connect', function() {
self.connectUrl = `http://${self.hostname}:${self.port}/?secret=${tools.encrypt(self.secret, self.options.key, self.options.iv)}&uuid=${self.options.uuid}`;
// 只有这些配置是有用的
let useOptions = [
'reconnection', 'reconnectionAttempts', 'hostname',
'port', 'reconnectionDelay', 'reconnectionDelayMax',
'timeout', 'autoConnect', 'transports', 'path'
];
let socketOptions = _.pick(self.options, useOptions);
let socketConnection = socketio(self.connectUrl, socketOptions);
socketConnection.on('connect', function() {
self.connected = true;
self._socket = _con;
reslove(_con)
self._socket = socketConnection;
reslove(socketConnection)
});
_con.on('reconnecting', function() {
console.log('reconnecting...');
socketConnection.on('reconnecting', function() {
logger.info('reconnecting...');
});
_con.on('reconnect', function() {
console.log('reconnected');
socketConnection.on('reconnect', function() {
logger.info('reconnected.');
self.emit('reconnect');
});
_con.on('connect_error', function(err) {
reject(err)
socketConnection.on('connect_error', function(err) {
reject(err);
});
_con.on('error', function(error) {
socketConnection.on('error', function(error) {
self.emit('error', error)
});
_con.on('disconnect', function(reason) {
// 断开后,在这里释放一些资源吧
socketConnection.on('disconnect', function(reason) {
self._socket = null;
self.connected = false;
const writeLog = {
let writeLog = {
reason: reason,
detail: 'disconnected from ' + self.connectUrl
}
};
self.emit('disconnect', writeLog)
});
});
}
......@@ -14,6 +14,7 @@
"license": "ISC",
"dependencies": {
"lodash": "^3.10.1",
"logl": "^1.1.0",
"nconf": "^0.8.2",
"socket.io-client": "^1.3.7"
}
......
......@@ -8,25 +8,28 @@ const nconf = require('nconf');
const EventEmitter = require('events').EventEmitter;
const tools = require('../lib/tools');
const socketio = require('../lib/con');
const logger = require('logl').getLogger('ConfigClient');
module.exports = ConfigClient;
function ConfigClient(socketConfig) {
if(!(this instanceof ConfigClient)) return new ConfigClient(socketConfig);
const defaultSocConfig = {
let defaultSocConfig = {
secret: 'secret',
key: 'key',
iv: 'iv'
}
//init local config file to cache
};
this.root = path.resolve(__dirname, '..');
this.nconf = nconf;
// 加载本地文件, 如果没有就新创建
this.nconf.file('config', this.root + '/config.json');
this.uuid = this.nconf.get('uuid') || tools.uuid();
this.nconf.set('uuid', this.uuid);
this.nconf.set('socketConfig', defaultSocConfig);
this.nconf.save();
defaultSocConfig.uuid = this.uuid;
_.assign(defaultSocConfig, socketConfig);
this.connect = false;
......@@ -34,26 +37,28 @@ function ConfigClient(socketConfig) {
this._socket = socketio(defaultSocConfig);
this._onErrors();
EventEmitter.call(this);
}
};
util.inherits(ConfigClient, EventEmitter);
ConfigClient.prototype._onErrors = function() {
const self = this;
let self = this;
//这些error要以http的形式上传
this._socket.on('error', function(err) {
console.log(err)
logger.error('socket error:', err);
});
this._socket.on('disconnect', function(err) {
self.connect = false;
console.log(err)
logger.error('socket disconnect:', err);
});
//断开重连后需要再次订阅
this._socket.on('reconnect', function() {
self._subscribe()
self._pull();
});
}
};
ConfigClient.prototype.connectSync = function() {
const self = this;
return this._socket.connect()
......@@ -63,53 +68,59 @@ ConfigClient.prototype.connectSync = function() {
self._onDatas();
return self;
});
}
};
ConfigClient.prototype._encrypt = function(str) {
if(typeof str !== 'string') {
str = JSON.stringify(str)
str = JSON.stringify(str);
}
return tools.encrypt(str,this.socketConfig.key, this.socketConfig.iv);
}
};
ConfigClient.prototype._decrypt = function(enStr) {
const _enStr = tools.decrypt(enStr, this.socketConfig.key, this.socketConfig.iv);
return JSON.parse(_enStr);
}
};
ConfigClient.prototype._setCache = function(datasArr) {
// 更新内存
for(let i = 0; i< datasArr.length; i++) {
this.nconf.set(datasArr[i].name, datasArr[i]);
}
// 更新磁盘
this.nconf.save();
}
};
//监听服务器发来的数据
ConfigClient.prototype._onDatas = function() {
const self = this;
if(this.connect) {
this.socket.on('data', function(res) {
// 解密
res = self._decrypt(res);
switch(res.type) {
case 'init':
self.emit('init:' + res.event, res.data);
self.emit('first', self); // return Promise
break;
case 'update':
console.log('update');
logger.info('update');
//这里需要更新相应的项目的配置
self.emit('update:' + res.event, res.data);
break;
case 'sys':
console.log('sys msg:', res.msg);
logger.info('sys msg:', res.msg);
break;
default:
console.log(res, 'unhandle res.type');
logger.warn('unhandle res.type', res);
}
})
}
}
};
// 使得在使用时更加简洁的语句表达, 增加代码的可读性
ConfigClient.prototype.use = function(cascadStr) {
if(cascadStr.indexOf('.') === -1) {
cascadStr += '.';
......@@ -119,38 +130,37 @@ ConfigClient.prototype.use = function(cascadStr) {
cascadStr = cascadStr.replace(/\./, '.config.').replace(/\./g,':');
}
return this.nconf.get(cascadStr);
}
};
ConfigClient.prototype._init = function(data) {
this._setCache(data);
}
};
ConfigClient.prototype._update = function(data) {
this._setCache(data);
//通知 server 已经接受
const receivedNotifiData = {
let receivedNotifiData = {
type: 'notifi',
data: data[0]['statusUuid']
}
};
this.socket.emit('data', this._encrypt(receivedNotifiData));
}
};
ConfigClient.prototype._on = function(name, resolve) {
name = name.join(':');
this.on('init:' + name, this._init);
this.once('first', resolve);
this.on('update:' + name, this._update);
}
};
ConfigClient.prototype._subscribe = function() {
this.socket.emit('data',this._encrypt(this.subData));
}
ConfigClient.prototype._pull = function() {
this.socket.emit('data', this._encrypt(this.subData));
};
ConfigClient.prototype.subscribe = function(projects, fn) {
const self = this;
let self = this;
return new Promise(function(resolve, reject) {
//TODO: 订阅之前要先检查当地的缓存
if(!Array.isArray(projects)) {
......@@ -163,7 +173,7 @@ ConfigClient.prototype.subscribe = function(projects, fn) {
self._on(projects, resolve);
if(self.connect) {
self._subscribe();
self._pull();
}
});
}
};
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment