Skip to content

Instantly share code, notes, and snippets.

@nagyv
Created June 3, 2018 19:58
Show Gist options
  • Save nagyv/9286a27dfd424bd155553a36e33abaa6 to your computer and use it in GitHub Desktop.
Save nagyv/9286a27dfd424bd155553a36e33abaa6 to your computer and use it in GitHub Desktop.
using Nes with Schmervice

This is a simple example to use Nes with Schmervice in hapipal-like project.

As there might be several susbcription channels, I prefer to separate them by domain, and have a single service that handles all the even passing between different parts of the code.

Example usage:

  // somewhere in a router's handler

  const { socketListenerService } = request.services()
  ...
  socketListenerService.emit('championshipUpdated', data)
'use strict'
const _ = require('lodash')
const Schmervice = require('schmervice')
class ChampionshipSocket extends Schmervice.Service {
// update the related championship team points
updateOnMatchResultUpdated () {
socketListenerService.on('matchResultUpdated', async ({ matchId }) => {
// ...
})
}
setUpSocket () {
const { Championship } = this.server.models()
const { socketListenerService } = this.server.services()
socketListenerService.subscription('/championship/{championshipId}', {
auth: false,
onSubscribe: async (socket, path, params) => {
// ...
}
})
socketListenerService.on('championshipUpdated', async ({ championshipId }) => {
// ...
})
}
initialize () {
this.setUpSocket()
this.updateOnMatchResultUpdated()
}
}
module.exports = ChampionshipSocket
'use strict'
const Schmervice = require('schmervice')
const EventEmitter = require('events')
class SocketListenerService extends Schmervice.Service {
constructor (server, options) {
super(server, options)
this.events = new EventEmitter()
}
subscription (path, config) {
this.server.subscription(path, config)
}
emit (event, data) {
return this.events.emit(event, data)
}
on (event, handler) {
return this.events.on(event, handler)
}
}
module.exports = SocketListenerService
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment