|
1 | 1 | import { HttpApiBuilder } from "@effect/platform"; |
2 | 2 | import { SqlClient, SqlResolver } from "@effect/sql"; |
3 | 3 | import { ServerApi, User } from "@local/api"; |
4 | | -import { Effect, Layer, Schema } from "effect"; |
| 4 | +import { Effect, flow, Function, Layer, Schema } from "effect"; |
5 | 5 | import { DatabaseLive } from "./database"; |
6 | 6 |
|
7 | 7 | export const RestApiLive = HttpApiBuilder.group(ServerApi, "rest", (handlers) => |
8 | | - handlers.handle("create-user", ({ payload }) => |
9 | | - Effect.gen(function* () { |
10 | | - const sql = yield* SqlClient.SqlClient; |
| 8 | + handlers |
| 9 | + .handle("create-user", ({ payload }) => |
| 10 | + Effect.gen(function* () { |
| 11 | + const sql = yield* SqlClient.SqlClient; |
11 | 12 |
|
12 | | - const InsertPerson = yield* SqlResolver.ordered("InsertPerson", { |
13 | | - Request: User.pipe(Schema.omit("id", "created_at")), |
14 | | - Result: User, |
15 | | - execute: (requests) => |
16 | | - sql` |
17 | | - INSERT INTO "user" |
18 | | - ${sql.insert(requests)} |
19 | | - RETURNING * |
20 | | - `, |
21 | | - }); |
| 13 | + const InsertPerson = yield* SqlResolver.ordered("InsertPerson", { |
| 14 | + Request: User.pipe(Schema.omit("id", "created_at")), |
| 15 | + Result: User, |
| 16 | + execute: (requests) => |
| 17 | + sql`INSERT INTO "user" ${sql.insert(requests)} RETURNING *`, |
| 18 | + }); |
22 | 19 |
|
23 | | - return yield* InsertPerson.execute({ name: payload.name }); |
24 | | - }).pipe( |
25 | | - Effect.tapError(Effect.logError), |
26 | | - Effect.mapError((error) => error.message) |
| 20 | + return yield* InsertPerson.execute({ name: payload.name }); |
| 21 | + }).pipe( |
| 22 | + Effect.tapError(Effect.logError), |
| 23 | + Effect.mapError((error) => error.message) |
| 24 | + ) |
| 25 | + ) |
| 26 | + .handle("get-user", ({ path }) => |
| 27 | + Effect.gen(function* () { |
| 28 | + const sql = yield* SqlClient.SqlClient; |
| 29 | + |
| 30 | + const GetById = yield* SqlResolver.findById("GetUserById", { |
| 31 | + Id: Schema.Number, |
| 32 | + Result: User, |
| 33 | + ResultId: (_) => _.id, |
| 34 | + execute: (ids) => |
| 35 | + sql`SELECT * FROM "user" WHERE ${sql.in("id", ids)}`, |
| 36 | + }); |
| 37 | + |
| 38 | + const getById = flow(GetById.execute, Effect.withRequestCaching(true)); |
| 39 | + |
| 40 | + return yield* getById(path.id).pipe(Effect.flatMap(Function.identity)); |
| 41 | + }).pipe( |
| 42 | + Effect.tapError(Effect.logError), |
| 43 | + Effect.mapError((error) => error.message) |
| 44 | + ) |
27 | 45 | ) |
28 | | - ) |
29 | 46 | ).pipe(Layer.provide(DatabaseLive)); |
0 commit comments