Skip to content

TrieRouter

reference
2 min readUpdated

Kind: Class

Source: src/router/trie-router/router.ts

Part of: Router

TrieRouter stores route patterns and their handlers in a trie-based route tree. Use add() to register a method and path, then call match() to resolve an incoming method and path to a Result<T>.

Implements: Router

Methods

MethodSignatureReturns
addadd(method: string, path: string, handler: T)void
matchmatch(method: string, path: string)Result<T>

Properties

PropertyType
namestring
#nodeNode<T>

Diagram

mermaid
graph LR
  Route[Route registration] --> Add[add()]
  Add --> Trie[Trie route tree]
  Request[Incoming method and path] --> Match[match()]
  Match --> Trie
  Trie --> Result[Result<T>]

Usage

ts
const router = new TrieRouter<string>()

router.add('GET', '/articles/:slug', 'getArticle')
router.add('POST', '/articles', 'createArticle')

const result = router.match('GET', '/articles/intro')

// Pass result to the request dispatcher.
console.log(result)

AI Coding Instructions

  • Keep the handler type consistent for every route registered in the same TrieRouter instance.
  • Register routes through add() before matching requests through match().
  • Pass the HTTP method and request path to match() using the same format used during registration.
  • Handle the returned Result<T> in the caller that dispatches matched handlers and processes route parameters.

How it works

Relationships

  • IMPORTS → checkOptionalParameter
  • IMPORTS → Node

Was this page helpful?

Download as PDF
TrieRouter — Hono (narrator proof)