Route params

To use params in your route simply prefix a wanted param with : like so: /user/:name

Additionally, you can specify extected parameters in Context generic type like so: Context<{ name?: string }>. It will give you better intellisense on context.request.params object

A route path is processed using path-to-regexp. It gives you a wide variety of patterns to use in the path. Learn more about it here

Here in the example we create a Map of users and then can access them via http requests to /user/:name route:

// params.ts
import { Application, HTTPResponse, HTTPStatus, Router, Context } from 'jsr:@sequoia/sequoia'

const app = new Application()
const router = new Router()

interface User {
    name: string
    age: number
}

const users = new Map<string, User>()
    .set('john', { name: 'John Sullivan', age: 20 })
    .set('megan', { name: 'Megan Fox', age: 35 })
    .set('april', { name: 'April Summer', age: 18 })

router.GET('/users', () => {
    const flatUserEntry = (v: [string, User]) => ({ [ v[0] ]: v[1] })
    const body = [...users.entries()].map(flatUserEntry)

    return new HTTPResponse({
        status: HTTPStatus.SUCCESS,
        type: 'application/json',
        body,
    })
})

router.GET(
    '/user/:name',
    (context: Context<{ name?: string }>) => {
        const { name } = context.request.params

        if (name) {
            const user = users.get(name)
            if (user) {
                return new HTTPResponse({
                    status: HTTPStatus.SUCCESS,
                    type: 'application/json',
                    body: user,
                })
            }
        }

        return new HTTPResponse({
            status: HTTPStatus.NOT_FOUND,
            type: 'application/json',
            body: {
                error: 'User was not found',
            },
        })
    },
)

app.useRouter(router)
await app.listen({ port: 8000 })

Run it with deno run --allow-net params.ts