Skip to content

andybee/arc-plugin-named-routes

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

24 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Named routes for Architect HTTP functions

Install

Into your existing Architect project:

npm i arc-plugin-named-routes

Add the following to your Architect project manifest (usually app.arc):

@plugins
arc-plugin-named-routes

Then modify any HTTP routes you wish to name to the verbose format and add a name:

@http
/foo
  method get
  name foo

Usage

Import the route() helper in to an HTTP function Lambda to use named routes:

// src/http/get-index/index.js
const route = require('arc-plugin-named-routes/route')

exports.handler = async () => ({
  statusCode: 200,
  headers: {
    'content-type': 'text/html; charset=utf8'
  },
  body: `
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
      <a href="${route('foo')}">Foo</a>
    </body>
    </html>
  `,
})

You must pass path parameters to route() if they exist in the route's path:

@http
/foo/:id
  method get
  name foo
route('foo', { id: 123 })

// returns: /foo/123

Any properties of the supplied object that do not match a path property are appended to the route in a query string:

route('foo', { id: 123, bar: 'bar' })

// returns: /foo/123?bar=bar

You can use the same name for two or more routes as long as each route has a unique method. The helper function will default to GET, then ANY. You can optionally supply an alternative method as the first argument:

@http
/foo/:id
  method get
  name foo
/bar
  method post
  name foo
route('foo', { id: 123 })

// returns: /foo/123

route('get', 'foo', { id: 123 })

// returns: /foo/123

route('post', 'foo')

// returns: /bar

When refactoring routes, to ease migration you can define multiple names for a single route (assuming no duplication, as above):

@http
/foo
  method get
  name foo bar
route('foo')

// returns: /foo

route('bar')

// returns: /foo

Configuration

If you wish to use the plugin for routes that are external to the current application, you can configure them using the @named-routes pragma in app.arc:

@named-routes
testing
  foo http://localhost:9876/foo/:id
staging
  foo https://example.org/foo/:id

Routes are defined against a stage. You can use path parameters in the usual way.

External routes will be interpreted as ANY method routes and prefixed with external.:

route('external.foo', { id: 123 })

// returns: http://localhost:9876/foo/123 in testing and https://example.org/foo/123 in staging