|
1 | 1 | import { Schema } from "@effect/schema"; |
2 | | -import { Context, Effect, Layer } from "effect"; |
| 2 | +import { Effect } from "effect"; |
3 | 3 | import { BuildPokeApiUrl } from "./BuildPokeApiUrl"; |
4 | 4 | import { FetchError, JsonError } from "./errors"; |
5 | 5 | import { PokemonCollection } from "./PokemonCollection"; |
6 | 6 | import { Pokemon } from "./schemas"; |
7 | 7 |
|
8 | | -const make = Effect.gen(function* () { |
9 | | - const pokemonCollection = yield* PokemonCollection; |
10 | | - const buildPokeApiUrl = yield* BuildPokeApiUrl; |
| 8 | +export class PokeApi extends Effect.Service<PokeApi>()("PokeApi", { |
| 9 | + effect: Effect.gen(function* () { |
| 10 | + const pokemonCollection = yield* PokemonCollection; |
| 11 | + const buildPokeApiUrl = yield* BuildPokeApiUrl; |
11 | 12 |
|
12 | | - return { |
13 | | - getPokemon: Effect.gen(function* () { |
14 | | - const requestUrl = buildPokeApiUrl({ name: pokemonCollection[0] }); |
| 13 | + return { |
| 14 | + getPokemon: Effect.gen(function* () { |
| 15 | + const requestUrl = buildPokeApiUrl({ name: pokemonCollection[0] }); |
15 | 16 |
|
16 | | - const response = yield* Effect.tryPromise({ |
17 | | - try: () => fetch(requestUrl), |
18 | | - catch: () => new FetchError(), |
19 | | - }); |
| 17 | + const response = yield* Effect.tryPromise({ |
| 18 | + try: () => fetch(requestUrl), |
| 19 | + catch: () => new FetchError(), |
| 20 | + }); |
20 | 21 |
|
21 | | - if (!response.ok) { |
22 | | - return yield* new FetchError(); |
23 | | - } |
| 22 | + if (!response.ok) { |
| 23 | + return yield* new FetchError(); |
| 24 | + } |
24 | 25 |
|
25 | | - const json = yield* Effect.tryPromise({ |
26 | | - try: () => response.json(), |
27 | | - catch: () => new JsonError(), |
28 | | - }); |
| 26 | + const json = yield* Effect.tryPromise({ |
| 27 | + try: () => response.json(), |
| 28 | + catch: () => new JsonError(), |
| 29 | + }); |
29 | 30 |
|
30 | | - return yield* Schema.decodeUnknown(Pokemon)(json); |
31 | | - }), |
32 | | - }; |
33 | | -}); |
34 | | - |
35 | | -export class PokeApi extends Context.Tag("PokeApi")< |
36 | | - PokeApi, |
37 | | - Effect.Effect.Success<typeof make> |
38 | | ->() { |
39 | | - static readonly Live = Layer.effect(this, make).pipe( |
40 | | - Layer.provide(Layer.mergeAll(PokemonCollection.Live, BuildPokeApiUrl.Live)) |
41 | | - ); |
42 | | -} |
| 31 | + return yield* Schema.decodeUnknown(Pokemon)(json); |
| 32 | + }), |
| 33 | + }; |
| 34 | + }), |
| 35 | + dependencies: [PokemonCollection.Live, BuildPokeApiUrl.Live], |
| 36 | +}) {} |
0 commit comments