-
Notifications
You must be signed in to change notification settings - Fork 20
/
readme-security-complex.ts
62 lines (53 loc) · 1.69 KB
/
readme-security-complex.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { NodeRuntime } from "@effect/platform-node"
import { Effect, Fiber, Layer, pipe, Schedule, Schema } from "effect"
import { Api, Client, Middlewares, RouterBuilder, Security } from "effect-http"
import { NodeServer } from "effect-http-node"
interface UserInfo {
email: string
}
class UserStorage extends Effect.Tag("UserStorage")<
UserStorage,
{ getInfo: (user: string) => Effect.Effect<UserInfo> }
>() {
static dummy = Layer.succeed(
this,
{ getInfo: (_: string) => Effect.succeed({ email: "email@gmail.com" }) }
)
}
const mySecurity = pipe(
Security.basic({ description: "My basic auth" }),
Security.map((creds) => creds.user),
Security.mapEffect((user) => UserStorage.getInfo(user))
)
const api = Api.make().pipe(
Api.addEndpoint(
pipe(
Api.post("endpoint", "/endpoint"),
Api.setResponseBody(Schema.String),
Api.setSecurity(mySecurity)
)
)
)
const app = RouterBuilder.make(api).pipe(
RouterBuilder.handle(
"endpoint",
(_, security) => Effect.succeed(`Logged as ${security.email}`)
),
RouterBuilder.build,
Middlewares.errorLog
)
Effect.gen(function*(_) {
const fiber = yield* pipe(app, NodeServer.listen({ port: 3000 }), Effect.fork)
const client = Client.make(api, { baseUrl: "http://localhost:3000" })
yield* pipe(
client.endpoint({}, Client.setBasic("patrik", "slepice")),
Effect.catchAllDefect(Effect.fail),
Effect.onError((e) => Effect.logWarning(`Api call failed with ${e}`)),
Effect.retry({ schedule: Schedule.spaced("1 second") }),
Effect.flatMap((response) => Effect.log(`Api call succeeded with ${response}`))
)
yield* Fiber.join(fiber)
}).pipe(
Effect.provide(UserStorage.dummy),
NodeRuntime.runMain
)