addNotification(notifications) { notifications = _.castArray(notifications); this.count.total = this.count.total + notifications.length; this.count.unread = this.count.unread + notifications.length; const timestamp = Date.now(); const notificationsToInsert = notifications.map(notification => ({ ts: timestamp, data: notification.data, id: notification.id, read: false, })); this.db.insert(notificationsToInsert, () => this.emitUpdate()); }
// for transport plugins integration onConnect (id) { if (this.hooks.onConnect) { return Promise.try(() => execHook(this.hooks.onConnect, this, id)) .then(loginData => _.castArray(loginData)) .catch(logError) } else { return Promise.resolve([]) } }
setAdapterOptions () { // adapter options compatibility this.adapterConstructor = this.transportOptions.adapter || this.options.adapter || 'memory' this.adapterOptions = _.castArray( this.transportOptions.adapterOptions || this.options.adapterOptions) const opts = { adapterConstructor: this.adapterConstructor, adapterOptions: this.adapterOptions } this.transportOptions = _.assign(opts, this.transportOptions) }
setEvents () { if (this.middleware) { const middleware = _.castArray(this.middleware) for (const fn of middleware) { this.nsp.use(fn) } } this.nsp.on('connection', socket => { return run(this, function * () { const id = socket.id const [userName, authData = {}] = yield this.server.onConnect(id) if (!userName) { return Promise.reject(new ChatServiceError('noLogin')) } yield this.server.registerClient(userName, id) this.confirmLogin(socket, userName, authData) }).catch(error => this.rejectLogin(socket, error)) }) }
constructor (server, options) { this.server = server this.options = options this.closed = false if (this.options.useCluster) { this.redis = new Redis.Cluster(...this.options.redisOptions) } else { const redisOptions = _.castArray(this.options.redisOptions) this.redis = new Redis(...redisOptions) } this.RoomState = RoomStateRedis this.UserState = UserStateRedis this.DirectMessagingState = DirectMessagingStateRedis this.lockTTL = this.options.lockTTL || 10000 this.instanceUID = this.server.instanceUID this.server.redis = this.redis for (const [cmd, def] of _.toPairs(luaCommands)) { this.redis.defineCommand(cmd, { numberOfKeys: def.numberOfKeys, lua: def.lua }) } }
function cleanup (services, sockets, done) { services = _.castArray(services) sockets = _.castArray(sockets) return Promise.try(() => { for (let i = 0; i < sockets.length; i++) { const socket = sockets[i] socket && socket.disconnect() } if (customCleanup) { return Promise.fromCallback(customCleanup) } else { return Promise.map(services, closeInstance) } }).timeout(3000).catch(Promise.TimeoutError, e => { console.log('Service closing timeout: ', e) }).finally(() => { customCleanup = null return cleanDB() }).asCallback(done) }