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-load-routes

v3.0.1

Published

koa@latest middleware to load routes from files and dirs using koa-router module

Downloads

16

Readme

koa-load-routes

NPM version Build Status Dependency Status Coverage Status

Koa middleware to load routes from files and directories using koa-router module

Warning

  • Node.js 8.0 and [email protected] or latest are required to use this module.
  • Since v2.0 koa-load-routes not support Generator Functions anymore (in favor of Async Functions).
  • Since v3.0 path option must be a absolute path
  • Since v3.0 firstMiddleware option was removed in favor of middlewares option.

Installation

$ npm install --save koa-load-routes

or

$ yarn add koa-load-routes
Options
  • String -> path (required)

    • Path from where the module will try to load the routes, if is a file, it will read the routes defined just inside of the file, otherwise, if is a directory, will read all .js files in the directory and load the routes inside each one.
  • Boolean -> recursive (optional, default: false)

    • If this argument is true the module will search route files recursive trhoug directories.
  • Array[Function|AsyncFunction] -> middlewares (optional)

    • A list of middlewares which will be added to each route loaded, can be Array of async functions or a normal functions or mixed, this middlewares will be attached previous to each route, useful by example for authentication middlewares.
  • String -> base (optional)

    • Adds the "base" string at the start of each loaded route url.
  • Array[any] -> args (optional)

    • Arguments to be pased inside the route main function, each array elements are passed as a independent argument (see examples below).
  • String -> suffix (optional, default: '.js')

    • If this argument is passed the module will load only the files which ends with the passed suffix + .js, by default if suffix is not supplied will try to load all files with .js extension.

Usage

app.js
const Koa = require('koa');
const loader = require('koa-load-routes');
const authMiddleware = require('./auth-middleware');
const path = require('path');

// Some module containing business logic and db access
const Interactors = require('./interactors');

var app = new Koa();

// Loading public routes
app.use(route({
  path: `${path.resolve()}/src/resources/public`,
  recursive: true,
  // Add /api/ at start of each loaded endpoint
  base: 'api',
  // Load files only ending with route.js
  suffix: 'route',
  // Injecting your business logic module
  args: [Interactors]
}));

// Loading private routes with auth middleware
app.use(route({
  path: `${path.resolve()}/src/resources/account`,
  recursive: true,
  base: 'api',
  suffix: 'route',
  middlewares : [authMiddleware()],
  args: [Interactors]
}));

app.listen(3000, () => {
  console.log('server started at http://127.0.0.1:3000/');
});
src/resources/public/login.route.js
module.exports = function (Interactors) {

  // Authentication endpoint
  this.post('/login', async ctx => {

    let userAccount = await Interactors.userAccount
      .getByEmail(ctx.request.body.email);

    if (!userAccount) {
      ctx.throw(404, 'Account not found');
    }

    if (ctx.body.password !== userAccount.password) {
      ctx.throw(403, 'Wrong Email/Password combination');
    }

   /*
    * You can create some kind of auth token here to
    * send it in body with user account info.
    * This is just an example
    */
    ctx.body = userAccount;
  });



  // Other possible routes examples

  this.get('/hello', (ctx, next) => {
    ctx.body = 'Hello world';
    return next();
  });

  // Routes chain
  this.get('/hello2', (ctx, next) => {
    ctx.body = 'hello world 2';
  })
  .get('/hello3', (ctx, next) => {
    ctx.body = 'hello world 3';
  });

  // Multiple middlewares
  this.post('/hello4', (ctx, next) => {
    console.log('im the first one');
    return next();
  },
  (ctx, next) => {
    ctx.body = 'yey!';
  });
};

License

MIT © Gonzalo Bahamondez