From 29bd394ebe003aa60c59d33462ffbd3e7c57a590 Mon Sep 17 00:00:00 2001 From: Kaan Barmore-Genc Date: Sun, 22 May 2022 00:33:51 -0400 Subject: [PATCH] add basic routing support --- example/index.ts | 35 ++++++++++++++++++++++++++++------- src/routing/router.ts | 24 +++++++++++++++++++++++- 2 files changed, 51 insertions(+), 8 deletions(-) diff --git a/example/index.ts b/example/index.ts index 7c327cb..1d931d0 100644 --- a/example/index.ts +++ b/example/index.ts @@ -1,17 +1,38 @@ import { endpoint } from "../src"; import { startServer } from "../src/core/server"; +import { route } from "../src/routing/router"; type Data = { name: string; }; startServer( - endpoint(async (req) => { - return { - status: 200, - body: { - name: "foo", + endpoint( + route([ + { + app: async (req) => { + return { + status: 200, + body: { + name: "foo", + }, + }; + }, + method: "GET", + url: "/", }, - }; - }), + { + app: async (req) => { + return { + status: 200, + body: { + name: "polo", + }, + }; + }, + method: "GET", + url: "/marco", + }, + ]), + ), ); diff --git a/src/routing/router.ts b/src/routing/router.ts index cb0ff5c..5d0256c 100644 --- a/src/routing/router.ts +++ b/src/routing/router.ts @@ -1 +1,23 @@ -export {}; +import type { Server } from "../compose"; +import type { BufferedResponse, Request } from "../core/bufferedServer"; + +export type Route = { + method: string; + url: string; + app: Server; +}; + +export function route( + routes: Route[], +): Server { + return async function route_(request) { + const { url, method } = request; + const route = routes.filter( + (registered) => registered.url === url && registered.method === method, + )[0]; + if (route) { + return route.app(request); + } + throw "No routes matched"; + }; +}