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

primus-route-handler

v2.0.1

Published

Connect express router to Primus.

Downloads

11

Readme

primus-route-handler

Declare your API via express router and communicate with it via Primus.io or Primus+primus-emitter (required for ack-callbacks) websocket.

API

This module exports single function

var ws_api_handler = require('primus-route-handler');

which returns a callback for your api requests:

spark.on('api', ws_api_handler(spark, router));

You can use anything else instead of 'api' here, but make sure that client uses the same channel.

Example

Server:

// sample routes
var router = require('express').Router();
router.use(checkAuth);
router.get('/user/:id', function (req, res) {
	... get user info from database ...
	res.send(userinfo);
});

...
var ws_api_handler = require('primus-route-handler');

primus.on('connection', function (spark) {
	spark.on('api', ws_api_handler(spark, router));
});

Client:

var socket = new Primus('http://localhost:3000');
// This triggers GET /user/:id route defined above:
socket.send('api', '/user/1234', function (err, userinfo) {
	if (err) {
		// handle error
		// err.status contains status code
		// err.statusText may contain further description
	}
	console.log('User info:', userinfo);
});

Simple way to specify path and optionally method is to use string argument of the form METHOD::PATH

socket.send('api', 'POST::/user', {name: 'john', age: 30}, cb);

Alternatively one can pass an object with fields path (/ by default), meth (get), headers ({content-type: 'application/json'}), query (if this field is not provided the query will be extracted from path and parsed):

socket.send('api', {meth: 'post', path: '/user'}, {name: 'john', age: 30}, cb);

Method defaults to 'get'.

Routes

You specify routes as usually with express 4 router (router module should work too.) In route callbacks req argument can be used to gather information about request and res allows to send response and set status. The same router may be usually mounted into your express app to handle AJAX requests.

req

Available standard express fields are: req.url, req.query (parsed with qs), req.body, req.method, req.headers={'content-type': 'application/json'} (default). Additionally req.spark is available in case you want to do something specific and do not plan to use this route for ajax. You can get original request object via req.spark.request.

res

To send client response use res.send(data). To set status use res.status(code [, description]).send(). res.send, res.end, res.json are all the same function.

Client library

Browserify users may require this module in client code to obtain simple api wrapper with standard methods get, post, put, delete and patch:

var socket = new Primus();
var api = require('primus-route-handler')(socket);
api.post('/user', {name: 'Vasja', age: 50}, function (err, res) {...});

Final handler

  • If there are no matching route or last route handler calls next() an error {status: 404, statusText: 'Not Found'} is sent to client.
  • If middleware calls next(ErrorObject) then error {status: ErrorObject.status || 500, statusText: ErrorObject.text || ErrorObject+''} is returned to client.
  • If next(ErrorCode) is used then {status: ErrorCode, statusText: ErrorCode+''} is sent.

restify

You can generate REST routes for your Mongoose models using express-restify-mongoose:

var router = express.Router();
var restify = require('express-restify-mongoose');
restify.serve(router, SomeMongooseModel);

Resulting router can be used to provide access to SomeMongooseModel over HTTP:

app.use(router);

as well as to provide the same routes over websocket:

primus.on('connection', function (spark) {
	spark.on('api', ws_api_handler(spark, router));
});

Other modules working with express.Router() should work with primus-route-handler too (with minor tweaks maybe). This is actually the whole point of this module -- to re-use existing code as much as possible.

License

MIT