forked from sukovanej/effect-http
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conflict-error-example.ts
53 lines (45 loc) · 1.54 KB
/
conflict-error-example.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
import { NodeRuntime } from "@effect/platform-node"
import { Schema } from "@effect/schema"
import { Context, Effect, pipe } from "effect"
import { Api, HttpError, Middlewares, RouterBuilder } from "effect-http"
import { NodeServer } from "effect-http-node"
import { debugLogger } from "./_utils.js"
const api = pipe(
Api.make({ title: "Users API" }),
Api.addEndpoint(
Api.post("storeUser", "/users").pipe(
Api.setResponseBody(Schema.String),
Api.setRequestBody(Schema.Struct({ name: Schema.String }))
)
)
)
interface UserRepository {
userExistsByName: (name: string) => Effect.Effect<boolean>
storeUser: (user: string) => Effect.Effect<void>
}
const UserRepository = Context.GenericTag<UserRepository>("UserRepository")
const mockUserRepository = UserRepository.of({
userExistsByName: () => Effect.succeed(true),
storeUser: () => Effect.void
})
const { storeUser, userExistsByName } = Effect.serviceFunctions(UserRepository)
const app = RouterBuilder.make(api).pipe(
RouterBuilder.handle("storeUser", ({ body }) =>
pipe(
userExistsByName(body.name),
Effect.filterOrFail(
(alreadyExists) => !alreadyExists,
() => HttpError.conflictError(`User "${body.name}" already exists.`)
),
Effect.andThen(storeUser(body.name)),
Effect.map(() => `User "${body.name}" stored.`)
)),
RouterBuilder.build,
Middlewares.errorLog
)
app.pipe(
NodeServer.listen({ port: 3000 }),
Effect.provideService(UserRepository, mockUserRepository),
Effect.provide(debugLogger),
NodeRuntime.runMain
)