npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

adonisjs-sse

v0.1.2

Published

An addon/plugin package to provide server-sent events functionality for AdonisJS 4.0+

Downloads

22

Readme

adonis-sse

An addon/plugin package to provide server-sent events functionality for AdonisJS 4.0+

NPM Version Build Status Coveralls

Getting Started


    adonis install adonisjs-sse

Usage

Firstly, follow the instructions in instructions.md file to setup the Provider and Middleware

See the instructions.md file for the complete installation steps and follow as stated.

Registering provider

Like any other provider, you need to register the provider inside start/app.js file.

const providers = [
  ...
  'adonisjs-sse/providers/ServerSentEventsProvider',
]

Registering middleware

Register the following middleware inside start/kernel.js file.

You can optionally place the sse middleware after the 'Adonis/Middleware/AuthInit' middleware

const globalMiddleware = [
  ...
  'Adonis/Middleware/AuthInit',
  'Adonis/Middleware/EventSourceWatcher'
]

Or alternatively setup the middleware as a named (use any name you feel like) middleware inside start/kernel.js file.


const namedMiddleware = {
  eventsource: 'Adonis/Middleware/EventSourceWatcher'
}

HINT: It would be much easier and better to make the EventSourceWatcher middleware a global middleware

Setup serve-sent events route inside start/routes.js file.


/** @type {typeof import('@adonisjs/framework/src/Route/Manager')} */
const Route = use('Route');

/**
 * If the 'eventsource' named middleware is set
 * then setup route like below
 */
Route.get('/stream', ({ source }) => {
      // send a server-sent events comment
      source.send("Hello AdonisJS", '!This is a comment!');
}).middleware(['eventsource']);

/**
 * If the middleware is a global middlware
 * then setup route like below
 */
Route.get('/stream', ({ source }) => {
      // send a server-sent events comment
      source.send("Hello AdonisJS", '!This is a comment!');
})

Route.post('/send/email', 'NotificationsController.sendEmail')

Example(s)

Setup a controller to dispatch server-sent events to the browser using the source.send(data: Object, comment: String, event: String, retry: Number) 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', 4000) // event: 'update', retry: 4000 (4 seconds)
			
        }
    }
}

module.exports = NotificationsController		

/**
 * source.send (METHOD)
 */

send( data: object, comment: string, event: string, retry: number );

Connecting from the client-side

<!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 id="server-side-events" type="text/javascript">
	     const stream = new EventSource("http://127.0.0.1:3333/stream");
	     
	     stream.addEventListener('message', function(e){
                 console.log("Data: ", e.data);
	     }, false);
	     
	     stream.addEventListener('open', function(e) {
		// Connection was opened.
	        console.log('connection open: true');
	     }, false);

	     stream.addEventListener('error', function(e) {
		  if (e.readyState == EventSource.CLOSED) {
		    // Connection was closed.
	            console.log('connection closed: true');
		  }
	     }, false);
     </script>
  </body>
</html>

License

MIT

Running Tests


    npm i

    npm run lint
    
    npm run test

Credits

Contributing

See the CONTRIBUTING.md file for info

Support

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.