connectionService.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. * connection statistics service
  3. * record connection, login count and list
  4. */
  5. var Service = function(app) {
  6. this.serverId = app.getServerId();
  7. this.connCount = 0;
  8. this.loginedCount = 0;
  9. this.logined = {};
  10. };
  11. module.exports = Service;
  12. var pro = Service.prototype;
  13. /**
  14. * Add logined userstate.
  15. *
  16. * @param uid {String} userstate id
  17. * @param info {Object} record for logined userstate
  18. */
  19. pro.addLoginedUser = function(uid, info) {
  20. if(!this.logined[uid]) {
  21. this.loginedCount++;
  22. }
  23. info.uid = uid;
  24. this.logined[uid] = info;
  25. };
  26. /**
  27. * Update userstate info.
  28. * @param uid {String} userstate id
  29. * @param info {Object} info for update.
  30. */
  31. pro.updateUserInfo = function(uid, info) {
  32. var user = this.logined[uid];
  33. if (!user) {
  34. return;
  35. }
  36. for (var p in info) {
  37. if (info.hasOwnProperty(p) && typeof info[p] !== 'function') {
  38. user[p] = info[p];
  39. }
  40. }
  41. };
  42. /**
  43. * Increase connection count
  44. */
  45. pro.increaseConnectionCount = function() {
  46. this.connCount++;
  47. };
  48. /**
  49. * Remote logined userstate
  50. *
  51. * @param uid {String} userstate id
  52. */
  53. pro.removeLoginedUser = function(uid) {
  54. if(!!this.logined[uid]) {
  55. this.loginedCount--;
  56. }
  57. delete this.logined[uid];
  58. };
  59. /**
  60. * Decrease connection count
  61. *
  62. * @param uid {String} uid
  63. */
  64. pro.decreaseConnectionCount = function(uid) {
  65. if(this.connCount) {
  66. this.connCount--;
  67. }
  68. if(!!uid) {
  69. this.removeLoginedUser(uid);
  70. }
  71. };
  72. /**
  73. * Get statistics info
  74. *
  75. * @return {Object} statistics info
  76. */
  77. pro.getStatisticsInfo = function() {
  78. var list = [];
  79. for(var uid in this.logined) {
  80. list.push(this.logined[uid]);
  81. }
  82. return {serverId: this.serverId, totalConnCount: this.connCount, loginedCount: this.loginedCount, loginedList: list};
  83. };