-
Notifications
You must be signed in to change notification settings - Fork 21
/
conflict-error-example.ts
50 lines (41 loc) · 1.46 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
import { NodeRuntime } from "@effect/platform-node"
import { Effect, Logger, pipe, Schema } from "effect"
import { Api, Handler, HttpError, Middlewares, RouterBuilder } from "effect-http"
import { NodeServer } from "effect-http-node"
class UserRepository extends Effect.Tag("UserRepository")<UserRepository, {
userExistsByName: (name: string) => Effect.Effect<boolean>
storeUser: (user: string) => Effect.Effect<void>
}>() {
static dummy = this.of({
userExistsByName: () => Effect.succeed(true),
storeUser: () => Effect.void
})
}
const storeUserEndpoint = Api.post("storeUser", "/users").pipe(
Api.setResponseBody(Schema.String),
Api.setRequestBody(Schema.Struct({ name: Schema.String }))
)
const api = pipe(
Api.make({ title: "Users API" }),
Api.addEndpoint(storeUserEndpoint)
)
const storeUserHandler = Handler.make(storeUserEndpoint, ({ body }) =>
Effect.gen(function*(_) {
const userRepository = yield* UserRepository
if (yield* userRepository.userExistsByName(body.name)) {
return yield* HttpError.conflict(`User "${body.name}" already exists.`)
}
yield* userRepository.storeUser(body.name)
return `User "${body.name}" stored.`
}))
const app = RouterBuilder.make(api).pipe(
RouterBuilder.handle(storeUserHandler),
RouterBuilder.build,
Middlewares.errorLog
)
app.pipe(
NodeServer.listen({ port: 3000 }),
Effect.provideService(UserRepository, UserRepository.dummy),
Effect.provide(Logger.pretty),
NodeRuntime.runMain
)