Routing
Here’s a @mapl/web API with a route that simply return Hi.
import { router, handle } from '@mapl/web';import { compileToHandlerSync } from '@mapl/web/compiler/jit';
const app = router([], [ handle.get('/', () => new Response('Hi'))]);
export default { fetch: compileToHandlerSync(app)};Run the server with srvx CLI:
npx srvx --port=8080 server.jsbun x --bun srvx --port=8080 server.jspnpx srvx --port=8080 server.jsyarn dlx srvx --port=8080 server.jsNavigate to http://localhost:8080, you should see Hi as the result.
Route patterns
Section titled “Route patterns”@mapl/web supports these patterns:
// From highest to lowest priority'/static' // Static routes'/user/*/dashboard' // Capture one path segment'/search/**' // Capture all path segments after '/search'Example usage:
const app = router([], [ handle.get( '/', () => new Response('Hi') ), // '/' => 'Hi'
handle.get( '/user/*', (id) => new Response('User: ' + id) ), // '/user/reve' => 'User: reve'
handle.get( '/search/**', (rest) => new Response('Search results for: ' + rest) ) // '/search/a/b' => 'Search results for: a/b']);Response handler
Section titled “Response handler”Response handler handles convert result type from route handler to a Response object.
const app = router([], [ handle.get('/', () => 'Hi', { type: handle.text }), // '/' => 'Hi']);Built-in response handlers:
handle.text; // Accepts BodyInithandle.json; // Accepts any type and serialize to JSONhandle.html; // Accepts BodyInit and automatically set HTML headersSubroutes
Section titled “Subroutes”Subroutes can be used to declare multiple routes with the same prefix.
const user = router([], [ handle.get('/profile', () => ...), handle.get('/login', () => ...)])
const app = router([], [ handle.get('/', () => ...)], { // register as /user/profile and /user/login '/user': user});