-
Notifications
You must be signed in to change notification settings - Fork 20
/
readme-security-custom.ts
36 lines (32 loc) · 1.15 KB
/
readme-security-custom.ts
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
import { HttpServerRequest } from "@effect/platform"
import { NodeRuntime } from "@effect/platform-node"
import { Effect, Logger, LogLevel, pipe, Schema } from "effect"
import { Api, HttpError, Middlewares, RouterBuilder, Security } from "effect-http"
import { NodeServer } from "effect-http-node"
const customSecurity = Security.make(
pipe(
HttpServerRequest.schemaHeaders(Schema.Struct({ "x-api-key": Schema.String })),
Effect.mapError(() => HttpError.unauthorized("Expected valid X-API-KEY header")),
Effect.map((headers) => headers["x-api-key"])
),
{ "myApiKey": { name: "X-API-KEY", type: "apiKey", in: "header", description: "My API key" } }
)
const api = Api.make().pipe(
Api.addEndpoint(
Api.post("myRoute", "/my-route").pipe(
Api.setResponseBody(Schema.String),
Api.setSecurity(customSecurity)
)
)
)
const app = RouterBuilder.make(api).pipe(
RouterBuilder.handle("myRoute", (_, apiKey) => Effect.succeed(`Logged as ${apiKey}`)),
RouterBuilder.build,
Middlewares.errorLog
)
app.pipe(
NodeServer.listen({ port: 3000 }),
Effect.provide(Logger.pretty),
Logger.withMinimumLogLevel(LogLevel.All),
NodeRuntime.runMain
)