An addon/plugin package to provide server-sent events functionality for AdonisJS 4.0+
adonis install adonisjs-sse
Setup serve-sent events route inside start/routes.js
file.
/** @type {typeof import('@adonisjs/framework/src/Route/Manager')} */
const Route = use('Route');
Route.get('/stream', ({ source }) => {
// send a server-sent events comment
source.send("Hello AdonisJS", '!This is a comment!');
})//.middleware(['eventsource']);
Route.post('/send/email', 'NotificationsController.sendEmail')
See the instructions.md file for the complete installation steps and follow as stated.
HINT: It would be much easier and better to make the
EventSourceWatcher
middleware a global middleware
Setup a controller to dispatch server-sent events to the browser using the
source.send()
method like so:
/** @type {typeof import('@adonisjs/mail/src/Mail')} */
const Mail = use('Mail')
class NotificationsController {
async sendEmail ({ request, auth, source }){
let input = request.only([
'ticket_user_id'
]);
let { id, email, fullname } = await auth.getUser();
let error = false
try{
await Mail.send(
'emails.template',
{ fullname }, (message) => {
message.to(email)
message.from('[email protected]')
message.subject('Ticket Creation Job Status')
})
}catch(err){
error = true
}finally{
source.send({
ticket_reciever: id,
ticket_creator: input.ticket_user_id,
ticket_mail_status: `email sent ${error ? 'un' : ''}successfuly`
}, null, 'update')
}
}
}
module.exports = NotificationsController
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Polyfill for older browsers without native support for the HTML5 EventSource API. -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=EventSource"></script>
</head>
<body>
<script>
let stream = new EventSource("http://127.0.0.1:3333/stream");
stream.onmessage = function(e){
console.log("Data: ", e.data);
};
</script>
</body>
</html>
MIT
npm i
npm run lint
npm run test
See the CONTRIBUTING.md file for info
Coolcodes is a non-profit software foundation (collective) created by Oparand - parent company of StitchNG, Synergixe based in Abuja, Nigeria. You'll find an overview of all our work and supported open source projects on our Facebook Page.
Follow us on facebook if you can to get the latest open source software/freeware news and infomation.
Does your business depend on our open projects? Reach out and support us on Patreon. All pledges will be dedicated to allocating workforce on maintenance and new awesome stuff.