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

@idio/router

v1.4.2

Published

The Router Utility For The Idio Web Server With Automatic Initialisation From Folders And Live Reload.

Downloads

449

Readme

@idio/router

npm version

@idio/router Is The Router Utility For The Idio Web Server With Automatic Initialisation From Folders And Live Reload.

yarn add @idio/router

Table Of Contents

API

The package is available by importing its default function:

import initRoutes, { watchRoutes } from '@idio/router'

async initRoutes(  router: !_goa.Router,  dir: string,  config=: !RoutesConfig,): !WatchConfig

The init function will scan files in the passed dir folder and add routes found for each method to the router. The default dir is src/routes and the config should be passed to control how the middleware and aliases are set up for each method.

  • router* !_goa.Router: An instance of the router.
  • dir* string: The directory from where to init routes.
  • config !RoutesConfig (optional): Additional configuration.

There are some rules when using this method:

  1. Each route module should export the default function which will be initialised as the middleware.
  2. The modules can also export the aliases property with an array of strings that are aliases for the route (alternatively, aliases can be specified via the configuration object — or when both ways are used, they are combined).
  3. The exported middleware property specifies any middleware chain constructor that will take precedence over the method middleware chain constructor from the config. When strings are passed, the middleware functions will be looked up in the middleware object returned by the idio's start method and passed in the configuration.
  4. If the exported middleware property is an array, the route will be the last one in the chain call. Otherwise, exporting a middleware chain constructor as a function allows to control the order of execution.

RoutesConfig: Options for the router.

For example, we can specify 1 GET and 1 POST route in the example/routes directory:

example/routes
├── get
│   └── index.js
└── post
    └── example.js

example/routes/get/index.js

export default async (ctx) => {
  const { test } = ctx
  ctx.body = `example get response: ${test}`
}

export const aliases = ['/']

// The router util will lookup the middleware by its name.
// The constructor is used to control the order.
export const middleware = (route) => {
  return ['example', route]
}

// Another way to write middleware is to use a plain array.
/* export const middleware = ['example'] */

example/routes/post/example.js

export default async (ctx) => {
  const { message } = ctx.request.body
  ctx.body = `example post response: ${message}`
}

// The aliases exported in the module will extend
// the ones specified in the config
export const aliases = ['/']

Then the router can be automatically configured.

import core from '@idio/idio'
import initRoutes from '@idio/router'

const Server = async () => {
  const { app, url, router, middleware } = await core({
    bodyparser: {
      middlewareConstructor() {
        return async (ctx, next) => {
          const data = await collect(ctx.req)
          ctx.req.body = JSON.parse(data)
          ctx.request.body = JSON.parse(data)
          await next()
        }
      },
    },
    example: {
      middlewareConstructor() {
        return async (ctx, next) => {
          ctx.test = 'test'
          await next()
        }
      },
    },
  })
  await initRoutes(router, 'example/routes', {
    middlewareConfig: {
      post(route) {
        return ['bodyparser', route]
      },
    },
    aliases: {
      post: {
        '/example': ['/example.html'],
      },
    },
    middleware,
  })
  app.use(router.routes())
  return { app, url }
}
http://localhost:5000
GET /
 :: example get response: test
POST "hello world" > / 
 :: example post response: hello world

chainRoute(  route: !Middleware,): !Array<string|!Middleware>

Receives the route and returns an ordered array of middleware.

  • route* !Middleware: The route.

async watchRoutes(  watchConfig: !WatchConfig,): !fs.FSWatcher

After the routes were initialised, it is possible to pass the value returned by the initRoutes method to the watchRoutes function to enable hot-route reload on the development environment. Every change to the module source code will trigger an update of the route including its aliases. The middleware and aliases changes are not currently implemented.

  • watchConfig* !WatchConfig: The watch config returned by the initRoutes method.
import idio from '@idio/idio'
import initRoutes, { watchRoutes } from '@idio/router'

const Server = async () => {
  const { app, url, router } = await idio({}, { port: 5001 })
  const w = await initRoutes(router, 'example/watch-routes')
  app.use(router.routes())
  let watcher
  if (process.env.NODE_ENV != 'production') {
    watcher = await watchRoutes(w)
  }
  return { app, url, watcher }
}
http://localhost:5001
GET / RESULT:
┌────────────────────────────────┐
│ [initial] example get response │
└────────────────────────────────┘
Update routes/get/index.js
⌁ example/watch-routes/get/index.js
.> hot reloaded GET /index /
GET / RESULT:
┌────────────────────────────────┐
│ [updated] example get response │
└────────────────────────────────┘

Copyright & License

GNU Affero General Public License v3.0