Use router

Router is a set of routes and handlers. Appis also Router.

There are two difference between App and Router

  • App never throws error while processing request. All requests that caused error and not responded will be captured and correctly finalized.
  • Router has no listen() method so it can't be started by self.

Router is used to by passing to router.route(). Different from router.handle()route() accept only string prefix for matching prefix of route.

import { createApp } from "https://servestjs.org/@v0.36.0/app.ts";
import { createRouter } from "https://servestjs.org/@v0.36.0/router.ts";

const app = createApp();
function IndexRoutes() {
  const router = createRouter();
  router.get("/", (req) => {
    // GET /
  });
  router.get("/about", (req) => {
    // GET /about
  });
  return router;
}
function UserRoutes() {
  const router = createRouter();
  router.get("/", (req) => {
    // GET /users
  });
  router.post("/", (req) => {
    // POST /users
  });
  router.get("/sign_in", (req) => {
    // POST /sign_in,
  });
  function UserPostRoutes() {
    const router = createRouter();
    router.get("/", (req) => {
      // GET /users/posts
    });
    router.get("/inbox", (req) => {
      // GET /users/posts/indbox
    });
    return router;
  }
  // Router can be nested
  router.route("/posts", UserPostRoutes());
  return router;
}

app.route("/", IndexRoutes());
app.route("/users", UserRoutes());
app.listen({ port: 8899 });