Routing
Mapl handles static routes, path parameters and wildcards.
router() // Capture and return the path value .get('/:user/name', (user) => user) // '/reve/name' -> 'reve' // Capture everything after '/' .get('/item/*', (item) => item) // '/item/a/b' -> 'a/b' // Multiple params .get('/:category/item/*', (category, id) => `${category}: ${id}`);
Mapl supports GET
, POST
, PUT
, DELETE
, PATCH
, OPTIONS
and TRACE
method by default.
router() // GET method .get(...) // POST method .post(...) // Similar method names for other methods // Handle all method .any(...);
Sub-routers
You can extend all routes of another instance.
const app = router() .get('/', () => 'Hi');
const anotherApp = router() .get('/', () => 'Hello API users!');
// To extend with no prefix, use '/' as the prefix valueapp.route('/api', anotherApp);
After calling app.route
, the app
instance has two registered routes, /
and /api
.
Compilation
Under the hood, Mapl inlines route patterns into optimized code paths to improve performance.
For example these routes:
router() .get('/', () => 'Hi') .get('/:user/name', (user) => user);
Will compile into:
// This is beautified with added comments for readability// @mapl/web@0.0.5(mwr) => { switch (mwr.method) { case "GET": { // Manual path parsing let mwru = mwr.url, ps = mwru.indexOf("/", 12) + 1, pe = mwru.indexOf("?", ps), p = pe === -1 ? mwru.slice(ps) : mwru.substring(ps, pe);
// Match static routes if (p === "") { return new Response(mp1()); }
// Dynamic path matching let l = p.length; { let j = p.indexOf("/"); if (j > 0) { let q0 = p.slice(0, j); if (p.startsWith("name", j + 1)) { if (l === j + 5) { return new Response(mp2(q0)); } } } } break; } } return mwnf;}
Performance
@mapl/web
underlying router (@mapl/router
) performs really well compared to others:
benchmark | avg | min | p75 | p99 | max |
---|---|---|---|---|---|
(api) mapl - compiled | 21.59 µs/iter | 19.08 µs | 20.35 µs | 43.58 µs | 426.21 µs |
(api) rou3 | 112.39 µs/iter | 97.03 µs | 108.25 µs | 199.49 µs | 2.65 ms |
(api) find-my-way | 79.52 µs/iter | 69.05 µs | 72.58 µs | 167.28 µs | 609.18 µs |
(api) hono - pattern | 92.03 µs/iter | 82.87 µs | 86.97 µs | 173.29 µs | 461.10 µs |
(api) hono - regexp | 49.63 µs/iter | 35.23 µs | 44.50 µs | 94.92 µs | 5.83 ms |
(api) hono - trie | 240.32 µs/iter | 220.36 µs | 235.02 µs | 480.32 µs | 822.80 µs |
You can check the benchmark here.