-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathwith-context.ts
More file actions
55 lines (47 loc) · 1.23 KB
/
with-context.ts
File metadata and controls
55 lines (47 loc) · 1.23 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
46
47
48
49
50
51
52
53
54
55
import { Elysia } from "elysia";
import { randomUUID } from "node:crypto";
import {
logger,
serializers,
serializeRequest,
type InferContext,
} from "../src";
/**
* the following coding shows how you can influence what is logged out:
*
* - request id based on "X-Request-ID"-header or random generation
* - additional properties based on your custom context
*/
const mySerializers = {
...serializers,
request: (request: Request) => {
const url = new URL(request.url);
return {
...serializeRequest(request),
// https://http.dev/x-request-id
id: request.headers.get("X-Request-ID") ?? randomUUID(),
path: url.pathname,
};
},
};
const myPlugin = () => new Elysia().decorate("myProperty", 42);
const app = new Elysia().use(myPlugin());
app
.use(
logger({
serializers: mySerializers,
customProps(ctx: InferContext<typeof app>) {
return {
params: ctx.params,
query: ctx.query,
myProperty: ctx.myProperty,
};
},
})
)
.get("/", (ctx) => {
ctx.log.info(ctx, "Context");
return "with-context";
})
.listen(3000);
console.log(`Listening on ${app.server!.url}`);