1.0.0 • Published 4 months ago

@curveball/router v1.0.0

Weekly downloads
56
License
MIT
Repository
github
Last release
4 months ago

Curveball Router

This package is a simple router for Curveball.

Installation

npm install @curveball/router

Getting started

The simplest, and recommended form works as follows:

import { Application } from '@curveball/kernel';
import router from '@curveball/router';

const app = Application();
app.use(
  router('/foo/:id', ctx => {
    // the 'id' is available via ctx.params.id
  })
);

It's also possible to do per-method routing, using the following syntax.

import { Application } from '@curveball/kernel';
import router from '@curveball/router';

const app = Application();
app.use(
  router('/foo/:id')
    .get( ctx => { /* GET requests */ })
    .post( ctx => { /* POST requests */ })
);

You can either specify 1, or multiple middlewares. The following example runs 2 fictional middlewares on a route.

const app = Application();

const route = router(
  '/foo/:id',
  myAuthMiddleware,
  myBodyparser,
  ctx => {
    ctx.response.body = 'success!';
  }
);

app.use(route);

Access matched route in other middleware

The matched route is added into the Curveball context for other middleware to access if they need (such as for access request logging). It will be accessible after the router has executed.

import { Application, Context } from '@curveball/kernel';
import router from '@curveball/router';

const app = Application();
app.use(async (ctx: Context, next) => {
  await next();

  // Will be '/foo/:id'
  const matchedRoute = ctx.router?.matchedRoute;
});

app.use(
  router('/foo/:id', ctx => {
    ctx.response.body = '/foo/' + ctx.state.params.id;
  });
);
1.0.0

4 months ago

0.6.0

1 year ago

0.5.0

2 years ago

0.4.2

2 years ago

0.4.1

2 years ago

0.4.0

2 years ago

0.3.0

3 years ago

0.3.0-beta.0

3 years ago

0.2.4

4 years ago

0.2.3

5 years ago

0.2.2

5 years ago

0.2.1

5 years ago

0.2.0

6 years ago

0.1.0

6 years ago

0.0.1

6 years ago