# Example: the pieces of a framework

> Status: implemented are markup as HTML, components of the server, their results, `Response`
> going up, `Content<T>`, component values with a result, decorators with guards, wrappers that
> take the body and the request context, routes, and `rooklang/server`; the server of the site, `site/server/main.rk`, is written
> with them, and the guide has a section on them. The decisions are collected at the end of the
> document, together with what is not decided yet. Server markup, components and `rooklang/server`
> remain **experimental** in 1.x and may change between releases.

> This document builds on [components.md](https://github.com/QWERN-9876r/RookLang/blob/HEAD/docs/components.md): components, decorators, context,
> components as values. It describes only what is different on the server.

The router, the middleware and the access checks below are ordinary Rook code; a framework would
put such pieces into a library.

```go
import { serve, reply, route, Route } from "rooklang/server"

interface User {
    name string
    role "admin" | "user"
}

const ROUTES Route<Html | Response>[] = [
    route("/", Home),
    route("/account", Account),
    route("/admin", Dashboard),
    route("/users/:id", UserPage),
]

dec session(request Request) {
    public const url = new URL(request.url)
    public const user ?User = await userOf(request)
}

@session(request)
comp App(request Request) {
    return <Logger><Router routes={ROUTES} /></Logger>
}

comp Logger<T>(children Content<T>) T {
    const started = Date.now()
    defer console.log(`${@session.url.pathname}: ${Date.now() - started} ms`)
    return await children()
}

comp Router(routes Route<Html | Response>[]) {
    for each in routes {
        const Page = each.match(@session.url.pathname)
        if Page != null {
            return <Page />
        }
    }
    return reply(<NotFound />, { status: 404 })
}

comp Account() {
    return <Private><Profile /></Private>
}

comp Private<T>(children Content<T>) {          // T | Response
    if @session.user == null {
        return Response.redirect("/login", 303)
    }
    return await children()
}

dec admin() {
    if @session.user?.role != "admin" {
        return reply("Forbidden", { status: 403 })
    }
    return (page Html) => <Layout title="Admin">{page}</Layout>
}

@admin
comp Dashboard() {
    const stats = await db.stats()
    return <main><h1>Stats</h1><p>{stats.users} users</p></main>
}

serve(App, { port: PORT })
```

- `Logger` reads `@session.path`, and the compiler infers the dependency from that read.
- `Router` is not special: a table of routes and `<Page />` of the one that matches; `/users/:id`
  gives `UserPage` its `id`.
- The guard is written twice, as a component (`Private`) and as a decorator (`admin`), to show both.
  A component fits a check that depends on where it is in the tree, a decorator one that belongs to
  the page itself.

