The Router For Creating Middleware For Goa Apps.
npm install @goa/router
@goa/router is The Router For Creating Middleware For Goa Apps.
``sh`
yarn add @goa/router
- Table Of Contents
- API
* Router
* RouterConfig
- Verbs
- Allowed Methods
* AllowedMethodsOptions
- Named Routes
- Multiple Middleware
- Nested Routes
- Router Prefixes
- URL Parameters
- Copyright & License
The package is available by importing its default class:
`js`
import Router from '@goa/router'
The example below creates a really simple router that responds to the GET / and POST /users/:uid requests. Because of allowedMethods, it will also send a response to the OPTIONS request with the allow header.
| Example | Output |
|---|---|
` const goa = new Goa() goa.use(router.allowedMethods()) | ` GET /Hello world POST /users/100You have edited the user 100 OPTIONS /HEAD, GET ` |
__Router__: Router For Goa Apps.
| Name | Type & Description |
|---|---|
| constructor | new (opts?: !RouterConfig) => Router |
Create a new router. const app = new Goa() router.get('/', (ctx, next) => { app | |
| static url | (path: string, ...params: !Object[]) => string |
Generate URL from url pattern and given params | |
| opts | !RouterConfig |
Stored options passed to the Router constructor. | |
| allowedMethods | (options: middleware generation.">!AllowedMethodsOptions) => method.">!Middleware |
Returns separate middleware for responding to OPTIONS const app = new Goa() app.use(router.routes()) | |
| param | (param: string, middleware: method.">!Middleware) => !Router |
Run middleware for named route parameters. Useful for auto-loading or validation. | |
| redirect | (source: string, destination: string, code?: number) => !Router |
Redirect source to destination URL with optional 30x status code.Both source and destination can be route names. | |
| route | (name: string) => Layer |
Lookup route with given name. If the route is not found, returns null. | |
| url | (name: string, ...params: !Object[]) => (string | !Error) |
Generate URL for route. Takes a route name and map of named params | |
| use | (path: (string | !Array<string> | method.">!Middleware), ...middleware: method.">!Middleware[]) => !Router |
Use given middleware. | |
| prefix | (prefix: string) => !Router |
Set the path prefix for a Router instance that was already initialized. | |
| middleware routesalias | () => method.">!Middleware |
Returns router middleware which dispatches a route matching the request. |
RouterConfig: Config for the router.
| Name | Type | Description |
| ---------- | ----------------------------- | --------------------------------------------------------------------------------------------- |
| methods | !Array<string> | The methods to serve.
Default HEAD, OPTIONS, GET, PUT, PATCH, POST, DELETE. |
| prefix | string | Prefix router paths. |
| routerPath | string | Custom routing path. |
Routes are assigned to the router by calling HTTP method verbs on the instance:
`js`
router
.get('/', (ctx, next) => {
ctx.body = 'Hello World!'
})
.post('/users', (ctx, next) => {
// ...
})
.put('/users/:id', (ctx, next) => {
// ...
})
.del('/users/:id', (ctx, next) => {
// ...
})
.all('/users/:id', (ctx, next) => {
// ...
})
Additionally, router.all() can be used to match against all methods. router.del() is an alias for router.delete().
When a route is matched, its path is available at ctx._matchedRoute and if named, the name is available at ctx._matchedRouteName.
Route paths will be translated to regular expressions using path-to-regexp.
Query strings will not be considered when matching requests.
The router can respond to the OPTIONS request with the allow header.
Example with Boom
`js
const app = new Goa()
const router = new Router()
app.use(router.routes())
app.use(router.allowedMethods({
throw: true,
notImplemented: () => new Boom.notImplemented(),
methodNotAllowed: () => new Boom.methodNotAllowed(),
}))
`
__AllowedMethodsOptions__: The options for the allowedMethods middleware generation.
| Name | Type | Description |
| ---------------- | --------------------- | -------------------------------------------------------------------------- |
| throw | boolean | Throw error instead of setting status and header. |
| notImplemented | () => !Error | Throw the returned value in place of the default NotImplemented error. |MethodNotAllowed
| methodNotAllowed | () => !Error | Throw the returned value in place of the default error. |
Routes can optionally have names. This allows generation of URLs and easy renaming of URLs during development.
`js
router.get('user', '/users/:id', (ctx, next) => {
// ...
})
router.url('user', 3)
// => "/users/3"
`
Multiple middleware may be passed to the router.
`js`
router.get(
'/users/:id',
async (ctx, next) => {
const user = await User.findOne(ctx.params.id)
ctx.user = user
await next()
},
ctx => {
console.log(ctx.user)
// => { id: 17, name: "Alex" }
}
)
It's possible to create a _Router_ instance, and then pass another _Router_ instance to its .use call to nest the two.
| Source | Output |
|---|---|
` posts.get('/', (ctx) => { goa.use(forums.routes()) | `
// GET /forums/123/posts/123 |
Route paths can be prefixed at the router level.
`js
const router = new Router({
prefix: '/users',
})
router.get('/', (ctx) => {
// responds to "/users"
ctx.body = ctx.params
})
router.get('/:id', (ctx) => {
// responds to "/users/:id"
ctx.body = ctx.params
})
goa.use(router.routes())
``js`
// Request /users
{}
// Request /users/123
{ id: '123' }
Named route parameters are captured and added to ctx.params.
`js
const router = new Router()
router.get('/:category/:title', (ctx) => {
// the params are exposed to the context.
ctx.body = ctx.params
})
goa.use(router.routes())
``js``
// Request /programming/how-to-node
{ category: 'programming', title: 'how-to-node' }
GNU Affero General Public License v3.0
Original Work by Alexander C. Mingoia under MIT License found in COPYING.
There's also a fork in the Koa org.
| © Idio 2019 |