Created
April 1, 2026 15:38
-
-
Save mattiamanzati/ca66c853f094c9b97122efa65bb63c8a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { Data, Effect, Layer, ServiceMap } from "effect" | |
| // third party API | |
| const ThirdPartyApi = { | |
| methodA: () => Promise.resolve(1), | |
| methodB: (arg: number) => Promise.resolve(arg * 2), | |
| } | |
| interface ThirdPartyApi { methodA: () => Promise<number>; methodB: (arg: number) => Promise<number> } | |
| // wrapper | |
| class ThirdPartyApiClientError extends Data.TaggedError("ThirdPartyApiClientError")<{ | |
| cause: unknown | |
| }> { } | |
| class ThirdPartyApiClient extends ServiceMap.Service< | |
| ThirdPartyApiClient, | |
| { | |
| readonly use: <A>(fn: (_: ThirdPartyApi) => Promise<A>) => Effect.Effect<A, ThirdPartyApiClientError> | |
| } | |
| >()("ThirdPartyApiClient") { | |
| static layer = (impl: ThirdPartyApi) => Layer.succeed(this, { | |
| use: cb => Effect.tryPromise({ | |
| try: () => cb(impl), | |
| catch: error => new ThirdPartyApiClientError({ cause: error }) | |
| }) | |
| }) | |
| } | |
| const program = Effect.gen(function* () { | |
| const api = yield* ThirdPartyApiClient | |
| const result = yield* api.use(_ => _.methodB(42)) | |
| console.log(result) | |
| }) | |
| program.pipe(Effect.provide(ThirdPartyApiClient.layer(ThirdPartyApi)), Effect.runPromise) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment