From 05831b364be1a5d965c1459319b3361847c7131f Mon Sep 17 00:00:00 2001 From: Emma Short Date: Sun, 10 Nov 2024 15:09:56 -0700 Subject: [PATCH] explicit return types --- router.ts | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 75 insertions(+), 2 deletions(-) diff --git a/router.ts b/router.ts index 0b86423..ed481ba 100644 --- a/router.ts +++ b/router.ts @@ -21,11 +21,84 @@ interface MiddlewareConfig { path: string; } +interface RouteConfigurator { + get(handler: Handler): RouteConfigurator; + post(handler: Handler): RouteConfigurator; + put(handler: Handler): RouteConfigurator; + delete(handler: Handler): RouteConfigurator; + patch(handler: Handler): RouteConfigurator; + options(handler: Handler): RouteConfigurator; +} + +/** + * A simple router for Deno + * + * @author Emmaline Autumn + * + * @example + * ```ts + * const router = new Router(); + * router.route('/users') + * .get((ctx) => { + * return new Response('GET /users'); + * }) + * .post((ctx) => { + * return new Response('POST /users'); + * }); + * + * router.route('/users/:id') + * .get((ctx) => { + * return new Response(`GET /users/${ctx.params.id}`); + * }) + * .put((ctx) => { + * return new Response(`PUT /users/${ctx.params.id}`); + * }) + * .delete((ctx) => { + * return new Response(`DELETE /users/${ctx.params.id}`); + * }); + * + * router.route('/posts') + * .get((ctx) => { + * return new Response('GET /posts'); + * }) + * .post((ctx) => { + * return new Response('POST /posts'); + * }); + * + * router.route('/posts/:id') + * .get((ctx) => { + * return new Response(`GET /posts/${ctx.params.id}`); + * }) + * .put((ctx) => { + * return new Response(`PUT /posts/${ctx.params.id}`); + * }) + * .delete((ctx) => { + * return new Response(`DELETE /posts/${ctx.params.id}`); + * }); + * + * router.route('/*') + * .get((ctx) => { + * return new Response('GET /*'); + * }) + * .post((ctx) => { + * return new Response('POST /*'); + * }); + * + * router.use('/users', async (_, next) => { + * console.log('Using middleware'); + * return await next(); + * }); + * + * Deno.serve({ + * port: 8000, + * handler: router.handle + * }); + */ export class Router { private routes: RouteConfig[] = []; private middleware: MiddlewareConfig[] = []; - route(path: string) { + route(path: string): RouteConfigurator { path = path.startsWith('/') ? path : `/${path}`; const pattern = new URLPattern({ pathname: path }); @@ -63,7 +136,7 @@ export class Router { }; } - use(pathOrMiddleware: string | Middleware, middlewareOrRouter?: Middleware | Router) { + use(pathOrMiddleware: string | Middleware, middlewareOrRouter?: Middleware | Router): Router { // Handle the case where only middleware is provided if (typeof pathOrMiddleware === 'function') { const pattern = new URLPattern({ pathname: '/*' });