-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.ts
More file actions
45 lines (40 loc) · 1.54 KB
/
Copy pathplugin.ts
File metadata and controls
45 lines (40 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* Plugins are plain functions from app to app — guards, derives and routes
* they add carry their types through .use().
*
* bun run examples/plugin.ts
*/
import { HttpError, Ma, mc } from "@ma/core"
import type { ContextState, RouteMap } from "@ma/core"
type User = { name: string; role: "admin" | "member" }
/** Auth plugin: derives a user from the authorization header and requires it. */
function auth<TCtx extends ContextState, TRoutes extends RouteMap>(app: Ma<TCtx, TRoutes>) {
return app
.derive((c) => ({
user:
c.header("authorization") === "Bearer valid"
? ({ name: "Alice", role: "admin" } as User)
: null,
}))
.guard<{ user: User }>((c) => {
if (!c.get("user")) throw new HttpError(401, { message: "log in first" })
})
}
const app = new Ma()
.get("/public", () => "anyone can read this")
.use(auth)
.get("/me", (c) => ({ name: c.get("user").name })) // user is User — narrowed, no null check
.group("/admin", (g) =>
g
.guard((c) => {
if (c.get("user").role !== "admin")
return Response.json({ message: "admins only" }, { status: 403 })
})
.get("/stats", () => ({ uptime: process.uptime() })),
)
const anonymous = mc(app)
console.log("public:", (await anonymous.public.get()).data)
console.log("me (no token):", (await anonymous.me.get()).status) // 401
const authed = mc(app, { headers: { authorization: "Bearer valid" } })
console.log("me:", (await authed.me.get()).data)
console.log("admin stats:", (await authed.admin.stats.get()).data)