Repository navigation
Expand file tree
/
Copy pathbasic.ts
More file actions
68 lines (54 loc) · 1.76 KB
/
Copy pathbasic.ts
File metadata and controls
68 lines (54 loc) · 1.76 KB
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
63
64
65
66
67
68
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FetchHttpClient from "effect/http/FetchHttpClient";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Fetch from "@monarcode/effetch";
const Todo = Schema.Struct({
id: Schema.Finite,
title: Schema.String,
done: Schema.Boolean,
});
const NewTodo = Schema.Struct({ title: Schema.String, due: Schema.Date });
const ApiError = Schema.Struct({ code: Schema.String, message: Schema.String });
const makeApi = Fetch.make({
baseUrl: "https://api.example.com",
headers: { accept: "application/json" },
defaultError: ApiError,
});
class Api extends Context.Service<Api, Effect.Success<typeof makeApi>>()(
"Api",
) {}
export const ApiLive = Layer.effect(Api)(makeApi).pipe(
Layer.provide(FetchHttpClient.layer),
);
export const program = Effect.gen(function* () {
const api = yield* Api;
const created = yield* api.post("/todos", {
input: NewTodo,
body: { title: "Write docs", due: new Date() },
output: Todo,
});
const todos = yield* api.get("/todos", {
query: { page: 1, done: false, tags: ["work", "urgent"] },
output: Schema.Array(Todo),
});
const updated = yield* api.patch("/todos/:id", {
params: { id: created.id },
body: { done: true },
output: Todo,
});
yield* api.del("/todos/:id", { params: { id: updated.id } });
return todos.length;
}).pipe(
Effect.catchTags({
HttpError: (error) =>
error.status === 404
? Effect.succeed(0)
: Effect.fail(error.body?.message ?? `HTTP ${error.status}`),
NetworkError: () => Effect.fail("You appear to be offline"),
DecodeError: (error) =>
Effect.fail(`Unexpected response: ${error.message}`),
}),
);
export const main = program.pipe(Effect.provide(ApiLive));