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

koa-router-groups

v1.0.0

Published

Middleware groups for koa-router.

Downloads

16

Readme

Middleware groups for koa-router

Requirements

  • requires node v7.6.0 or higher for ES2015 and async function support

Installation

Run the npm install command:


npm i koa-router-groups --save
# or
yarn add koa-router-groups

After installing koa-router-groups, all you need to do is extend an existing koa router instance with the extend function.

const Koa = require("koa");
const KoaRouter = require("koa-router");
const KoaRouterGroups = require("koa-router-groups");

let koa = new Koa();
let koaRouter = new KoaRouter();
KoaRouterGroups.extend(koaRouter);

Quick Example


const Koa = require("koa");
const KoaRouter = require("koa-router");
const KoaRouterGroups = require("koa-router-groups");

let app = new Koa();
let router = new KoaRouter();
KoaRouterGroups.extend(router); // Extend the router with "registerMiddleware", "pushMiddleware", "popMiddleware" and "group" functions.

// Register some middleware functions.
router.registerMiddleware("logger", async (ctx, next) => { /* Middleware function. */ });
router.registerMiddleware("body", async (ctx, next) => { /* Middleware function. */ });
router.registerMiddleware("auth", async (ctx, next) => { /* Middleware function. */ });
router.registerMiddleware("auth.admin", async (ctx, next) => { /* Middleware function. */ });
router.registerMiddleware("auth.root", async (ctx, next) => { /* Middleware function. */ });

// Push 3 middleware functions that every route will use to the stack.
router.pushMiddleware("logger", async (ctx, next) => { /* Middleware function. */ }, "body");

router.group("auth", () => {

	// ... define routes here that need to pass "auth" middleware ...

	router.group("auth.admin", () => {
		// ... define routes here that need to pass "auth" and "auth.admin" middleware ...
	});

	router.group("auth.root", () => {
		// ... define routes here that need to pass "auth" and "auth.root" middleware ...
	});
});

// Remove the 3 middlewares that were pushed to the stack.
router.popMiddleware();

app.use(router.routes()).use(router.allowedMethods());

// Start the server.
let server = app.listen(process.env.SERVER_PORT || 3000);

// ...

Functions

.registerMiddleware(name, middleware)

/**
 * Registers the middleware so that it can be called/used with the reference name string instead of directly using the function definition.
 * 
 * @param {string} name Middleware name for reference.
 * @param {function} middleware Middleware function.
 */

.pushMiddleware(...middleware)

/**
 * Push a batch of middleware functions to the top of the middleware stack.
 * 
 * @param {...function} ...middleware Batch of middleware functions.
 */

.popMiddleware()

/**
 * Pops the batch of middleware functions that is on top of the middleware stack.
 */

.group(...middleware, callback)

/**
 * Group routes that use the same middleware.
 * 
 * @param {...function} ...middleware Batch of middleware functions.
 * @param {function} callback Callback wrapper function. Any routes within this function will have to pass the batch of middleware function.
 */

Full Example

A working example can be found in this repository. You can start it by running the example/example.js file. If you want to read the source of the example you can download the example.zip and extract it to a folder. The most important files in the example are example/example.js and example/example-routes.js.

Contents of example/example.js - this is the server file


"use strict";

const Koa = require("koa");

// Require middlewares.
const mwResponseTime = require("./middleware/response-time");
const mwLogger = require("./middleware/logger");
const mwOptions = require("./middleware/options");
const mwErrorHandler = require("./middleware/error-handler");

// Require router.
const routes = require("./example-routes");

// Server setup.
let app = new Koa(); // Create a Koa server instance.
// Define which middleware every request will have to pass through:
app.use(mwResponseTime);
app.use(mwLogger);
app.use(mwOptions);
app.use(mwErrorHandler);

// Apply routes.
let router = routes(app);

// Start the server.
let server = app.listen(process.env.SERVER_PORT || 3000);
if (server.address() === null) {
	let errMsg = 'Error: Please select a different server port by configuring the ".env" file.';
	console.error(errMsg);
	process.exit(1);
}
console.log("Server: http://127.0.0.1:" + server.address().port);

Contents of example/example-routes.js - this is the routes file


"use strict";

const KoaRouter = require("koa-router");
const KoaRouterGroups = require("koa-router-groups");

// Require middlewares.
const mwBodyParser = require("koa-bodyparser");
const mwAuth = require("./middleware/auth");

// Require controllers.
const Controller = require("./controllers/exmaple-controller");

// Route definitions.
module.exports = function (app) {
	// Create Koa Router.
	let router = new KoaRouter();
	KoaRouterGroups.extend(router); // Extend the router with "group" and "registerMiddleware" functions.
	
	// Register middlewares.
	router.registerMiddleware("body", mwBodyParser({
		jsonLimit: '50mb',
		formLimit: '50mb',
		textLimit: '50mb',
	}));
	router.registerMiddleware("auth", mwAuth);

	// Push the middleware used by all routes to the stack.
	router.pushMiddleware("body");

	// Define API functions.
	router.get("auth.login", "/login", Controller.login);

	// Auth group. Any routes in this group need to pass the "AuthMiddleware.auth" middleware.
	router.group("auth", () => {
		// Logout route.
		router.get("auth.logout", "/logout", Controller.logout);

		// Get protected data.
		router.get("data.index", "/data", Controller.index);
	});

	// Apply the routes to the app.
	app.use(router.routes()).use(router.allowedMethods());

	return router;
};