forked from effect-app/boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRequestContextMiddleware.ts
More file actions
46 lines (40 loc) · 1.83 KB
/
RequestContextMiddleware.ts
File metadata and controls
46 lines (40 loc) · 1.83 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
import { setupRequestContext } from "@effect-app/infra/api/setupRequest"
import { RequestContext } from "@effect-app/infra/RequestContext"
import { HttpMiddleware, HttpServerRequest, HttpServerResponse } from "api/lib/http"
import { Effect, S } from "effect-app"
import { RequestId } from "effect-app/ids"
import { NonEmptyString255 } from "effect-app/schema"
export const RequestContextMiddleware = HttpMiddleware.make((app) =>
Effect.gen(function*($) {
const req = yield* $(HttpServerRequest.ServerRequest)
const currentSpan = yield* $(Effect.currentSpan.orDie)
const parent = currentSpan?.parent ? currentSpan.parent.value : undefined
const start = new Date()
const supported = ["en", "de"] as const
const desiredLocale = req.headers["x-locale"]
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const locale = desiredLocale && supported.includes(desiredLocale as any)
? (desiredLocale as typeof supported[number])
: ("en" as const)
const requestId = req.headers["request-id"]
const rootId = parent?.spanId
? RequestId(parent.spanId)
: requestId
? S.decodeUnknownSync(RequestId)(requestId)
: RequestId.make()
const storeId = req.headers["x-store-id"]
const namespace = S.NonEmptyString255((storeId && (Array.isArray(storeId) ? storeId[0] : storeId)) || "primary")
const requestContext = new RequestContext({
id: currentSpan?.spanId ? RequestId(currentSpan.spanId) : RequestId.make(),
rootId,
name: NonEmptyString255(req.originalUrl), // set more detailed elsewhere
locale,
createdAt: start,
namespace
})
const res = yield* $(setupRequestContext(app, requestContext))
return res.pipe(
HttpServerResponse.setHeaders({ "request-id": requestContext.rootId, "Content-Language": requestContext.locale })
)
})
)