Skip to content

Instantly share code, notes, and snippets.

@mikield
Created September 26, 2017 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikield/b3645f35b89958b0797f1fe389e8112b to your computer and use it in GitHub Desktop.
Save mikield/b3645f35b89958b0797f1fe389e8112b to your computer and use it in GitHub Desktop.
Notify a user to Private channel with Laravel Echo Server + Broadcaster
'use strict'
/*
* Applicaiton-Nofifier
*
* (c) Vladyslav Gaysyuk <mikield@icloud.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
const { ServiceProvider } = require('@adonisjs/fold')
class NotificationServiceProvider extends ServiceProvider {
/**
* The register method called by ioc container
* as a life-cycle method
*
* @method register
*
* @return {void}
*/
register () {
const Broadcaster = this.app.use('Broadcaster')
this.app.bind('Notification', (app) => {
return class Notify {
constructor(){
this.Broadcaster = Broadcaster
this.Notification = this.Broadcaster.event('notification')
}
to(user){
this.Notification.into('private-user-state.'+user.id)
return this
}
with(data){
this.Notification.with(data)
return this
}
withError(error){
this.Notification.with({error})
return this
}
send(){
this.Notification.broadcast()
}
}
})
}
}
module.exports = NotificationServiceProvider
@mikield
Copy link
Author

mikield commented Sep 26, 2017

Before use

Before using this code please take a look at https://gist.github.com/mikield/45c8997e05b5ab0e71a56009ad955f33
Cause this code uses Broadcaster service.

Subscribe user from client side to private channel, and set it into the code.

For example:

Echo.private('user-state.' + user.id).on('notification', (event) => {
  if(event.error !== undefined){
     alert(event.error)
  }
})

Ho to use?

let user = await User.find(1)
const Notification = use('Notification')
new Notification().to(user).withError('WowSuchError').send()

Or

let user = await User.find(1)
const Notification = use('Notification')
new Notification().to(user).with({message: "Drop the table task is finished").send()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment