Notifications (adonis+vuejs)


#1

Hello everyone, I’m developing an API with AdonisJS which has a cms VueJS based and a frontend also in VueJS. Let’s say, users will sign up in the frontend and I need notifications to appear “real time” in the cms that will say a new user registered. Right now I just added a function that checks the database passing throu Adonis api (im using axios for that), at every page reload, but I wanted to know if somehow was possible to just “keep checking the db/api” so the admin won’t have to reload the page to see the notification. I’m also not sure if I should ask this in a VueJS forum rather then Adonis… But if someone has any ideas would be greatly appreciated :wink:

After I posted and may have found something… Is my answer here?
https://adonisjs.com/docs/4.1/websocket :thinking:


#2

Yes it is, you can reuse the ws websocket for your fronend in vuejs and connect to the websocket server / Adonis “back”, is a Websocket abstraction that you can reuse. Something else you can try is socket.io is going to give you more ideas about how websockets work in nodejs.

Regards


#3

Thank you, I will try out to configure the websocket server in Adonis and then the client https://adonisjs.com/docs/4.1/websocket-client in VueJS, i’ll share what it will come out of it. :smiley:


#4

I actually seem to have solved! It’s working and it’s awesome :yum:
I understood that I needed to configure at least one client socket to be able to test the event emitter from my http controller (I was otherwise getting “cannot read property ‘broadcast’ of null” error).
Hoping to help someone else working with VueJS I actually lost hours around the issue “regeneratorRuntime is not defined” - looks like I didn’t only need to import @babel/polyfill - everything I googled said so - but also to modify my babel.config.js adding useBuiltIns parameter like so:

babel.config.js

module.exports = {
  presets: [['@vue/app', { useBuiltIns: 'entry' }]],
  plugins: ['@babel/plugin-transform-regenerator']
};

Of course @babel/plugin-transform-regenerator and @babel/polyfill need to be downloaded from npm and then import @babel/polyfill before everything else in the main.js file.
For now I then only added in the vuejs main.js

import Ws from '@adonisjs/websocket-client';
const ws = Ws('ws://127.0.0.1:3333');
ws.connect();
ws.on('open', () => {
  console.log('connected!');
});
ws.on('close', () => {
  console.log('not connected!');
});
/** subscribe to user channel **/
const wsUser = ws.subscribe('user');
/** listener to my event **/
wsUser.on('store', user => {
  console.log('new user' + user);
});

Thanks and happy coding :tada: