Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/idiocc/router
The Router Utility For The Idio Web Server With Automatic Initialisation And Live Reload.
https://github.com/idiocc/router
goa middleware router server
Last synced: 2 days ago
JSON representation
The Router Utility For The Idio Web Server With Automatic Initialisation And Live Reload.
- Host: GitHub
- URL: https://github.com/idiocc/router
- Owner: idiocc
- License: agpl-3.0
- Created: 2018-11-17T19:40:04.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2020-02-26T15:44:07.000Z (over 4 years ago)
- Last Synced: 2024-10-13T13:21:19.178Z (25 days ago)
- Topics: goa, middleware, router, server
- Language: JavaScript
- Homepage: https://www.idio.cc
- Size: 180 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# @idio/router
[![npm version](https://badge.fury.io/js/%40idio%2Frouter.svg)](https://www.npmjs.com/package/@idio/router)
![Node.js CI](https://github.com/idiocc/router/workflows/Node.js%20CI/badge.svg)`@idio/router` Is A Router Utility For The [_Idio Web Server_](https://github.com/idiocc/idio) With Automatic Initialisation From Folders And Live Reload.
```sh
yarn add @idio/router
npm i @idio/router
```## Table Of Contents
- [Table Of Contents](#table-of-contents)
- [API](#api)
- [`async initRoutes(router, dir, config=): !WatchConfig`](#async-initroutesrouter-_goarouterdir-stringconfig-routesconfig-watchconfig)
* [`RoutesConfig`](#type-routesconfig)
* [`chainRoute(route: !Middleware): !Array`](#chainrouteroute-middleware-arraystringmiddleware)
- [`async watchRoutes(watchConfig): !fs.FSWatcher`](#async-watchrouteswatchconfig-watchconfig-fsfswatcher)
- [Copyright & License](#copyright--license)## API
The package is available by importing its default function:
```js
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.
1. 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).
1. 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.
1. 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.
Name
Type & Description
middlewareConfig
!Object<string, !chainRoute>
The method-level middleware configuration: for each method it specifies how to construct the middleware chain. If the string is found in the chain, the middleware will be looked up in themiddleware
object.
middleware
!ConfiguredMiddleware
The configured middleware object return by the Idio'sstart
method.
aliases
!Object<string, !Array<string>>
The map of aliases. Aliases can also be specified in routes by exporting thealiases
property.
filter
(filename: string) => boolean
The filter for filenames. Defaults to importing JS and JSX.
filename*string
: The filename.
For example, we can specify 1 `GET` and 1 `POST` route in the `example/routes` directory:
```m
example/routes
├── get
│ └── index.js
└── post
└── example.js
```*example/routes/get/index.js*
```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*
```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.
```js
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
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.
```js
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