did more docs

This commit is contained in:
2025-01-04 18:37:29 -07:00
parent 0c8d1865ff
commit 5dad5bc0b1
4 changed files with 64 additions and 3 deletions

View File

@@ -76,6 +76,22 @@ export class Router {
private routes: RouteConfig[] = [];
private middleware: MiddlewareConfig[] = [];
/**
* @description defines a new route
* @param path the path to match, uses the same syntax as the URLPattern constructor
* @returns a RouteConfigurator object
*
* @example
* ```ts
* router.route('/users')
* .get((req, ctx) => {
* return new Response('GET /users');
* })
* .post((req, ctx) => {
* return new Response('POST /users');
* });
* ```
*/
route(path: string): RouteConfigurator {
path = path.startsWith("/") ? path : `/${path}`;
@@ -114,6 +130,20 @@ export class Router {
};
}
/**
* @description adds a middleware to the router
* @param pathOrMiddleware the path to match, uses the same syntax as the URLPattern constructor
* @param middlewareOrRouter the middleware to add, or a Router object to nest routes
* @returns the Router object
*
* @example
* ```ts
* router.use('/users', async (req, ctx, next) => {
* console.log('Using middleware');
* return await next();
* });
* ```
*/
use(
pathOrMiddleware: string | Middleware,
middlewareOrRouter?: Middleware | Router,
@@ -184,6 +214,19 @@ export class Router {
return this;
}
/**
* @description handles incoming requests
* @param req the incoming request
* @returns a Response object
*
* @example
* ```ts
* Deno.serve({
* port: 8000,
* handler: router.handle
* });
* ```
*/
handle = async (req: Request): Promise<Response> => {
const url = new URL(req.url);
const method = req.method;
@@ -303,6 +346,18 @@ export class Router {
: `${normalizedBase}/${normalizedRoute}`;
}
/**
* @description serves a directory as a static website
* @param dir the directory to serve
* @param root the root path to serve the directory from
* @param opts optional options
* @returns the Router object
*
* @example
* ```ts
* router.serveDirectory('/public', './public');
* ```
*/
serveDirectory(dir: string, root: string, opts?: { showIndex: boolean }) {
this.route(root + "*").get(async (_req, ctx) => {
const { showIndex } = opts ?? { showIndex: false };