Router/README.md

2.1 KiB
Executable File

BearMetal Router

A simple router for Deno.

License: GPL v3

Usage

Basics

import Router from "@bearmetal/router";

const router = new Router();

router
  .route("/users")
  .get((req, ctx) => {
    return new Response("GET /users");
  })
  .post((req, ctx) => {
    return new Response("POST /users");
  });

Deno.serve(router.handle);

Middleware

...

router.use('/users', async (ctx, next) => {
  console.log('Executing middleware');
  return await next();
});

...

Nested Routers

...

const nestedRouter = new Router();

nestedRouter
  .route('/users')
  .get((req, ctx) => {
    return new Response('GET /users');
  })
  .post((req, ctx) => {
    return new Response('POST /users');
  });

router.use('/users', nestedRouter);

...

Static Files

...
router.serveDirectory('dirname', '/url-root') // files from 'dirname' directory will be available at '/url-root/filename'

// To automatically locate index.html pages:
router.serveDirectory('dirWithIndexHtml', '/indexes', {showIndex: true});
// Will also generate an index if there is no index.html present in the directory
...

File-based Routing

Note: This is an experimental feature and may change in the future. Currently, JSR does not support dynamic imports for external modules in Deno. In order to use this feature, you will need to install as an HTTP module (available soon).

import { FileRouter } from "@bearmetal/router";

const router = new FileRouter("dirname");
Deno.listen(router.handle);

// dirname/index.ts - will be accessible at '/'
export default function (req, ctx) {
  return new Response("Hello, world!");
}

// dirname/methods.ts - will be accessible at '/methods'
export const handlers = {
  get() {
    return new Response("Hello, world");
  },
  post(req, ctx) {
    const data = doDataOp(req.body);
    return new Response(data);
  },
};

// dirname/nestedRouter.ts - will be accessible at '/nestedRouter'
import { router } from "@bearmetal/router";

const router = new Router();
export default router;