Represents a Subway router that manages routes and their handlers.
Example 1
Example 1
import { type SubwaySub, Subway } from 'jsr:@km/subway'; import { SimpleRoute } from 'jsr:@km/subway/routes/simple.ts'; type Result = Promise<any>; class Context { constructor(public readonly req: Request) {} } class Route extends SimpleRoute<Context, Result> { obtain_valid_json<T>(schema: { validate: (data: unknown) => Promise<T> }) { return async (ctx: Context) => schema.validate(await ctx.req.json()); } } const Router = new Subway(Route); const sample_route_middleware = (route: Route) => { route.use(async (ctx, next) => { console.log('before'); const result = await next(ctx); console.log('after'); return result; }); }; const sample_group_middleware = (scope: SubwaySub<Route>) => { scope.use(sample_route_middleware); }; Router.sub('user', (scope) => { scope.sub('friends', (scope) => { sample_group_middleware(scope); scope.add('get', async (ctx) => {}); }); scope.cast('set', (route) => { sample_route_middleware(route); const obtain = route.obtain_valid_json({ validate: async (data) => data }); return async (ctx) => { const data = await obtain(ctx); }; }); }); Deno.serve(async (req) => { const route = Router.find(new URL(req.url).pathname)!; const result = await route.execute(new Context(req)); return new Response(result); });
private
middlewares: Middleware<R>[]
Casts a new route with the specified action using the provided factory.
clear(): void
Clears all routes from the router.
Creates a group of routes using the provided factory.
Creates a sub-router with the specified prefix and callback.
Returns an iterator for all routes in the router.
use(middleware: Middleware<R>): void
Adds a middleware to the router.