| 1 | /** |
| 2 | * @title Using Effect.fn and Effect.fnUntraced |
| 3 | * |
| 4 | * When writing reusable functions that return an Effect, use `Effect.fn` or |
| 5 | * `Effect.fnUntraced` to use the generator syntax. |
| 6 | * |
| 7 | * Use `Effect.fn("name")` when the function should create a tracing span. Prefer |
| 8 | * `Effect.fnUntraced` when tracing is not needed, particularly for library |
| 9 | * implementations and hot paths. |
| 10 | * |
| 11 | * **Avoid creating functions that only wrap and return an `Effect.gen`**. |
| 12 | */ |
| 13 | |
| 14 | import { Effect, Schema } from "effect" |
| 15 | |
| 16 | // Pass a string to Effect.fn, which will improve stack traces and also |
| 17 | // attach a tracing span (using Effect.withSpan behind the scenes). |
| 18 | // |
| 19 | // The name string should match the function name. |
| 20 | // |
| 21 | export const effectFunction = Effect.fn("effectFunction")( |
| 22 | // You can use `Effect.fn.Return` to specify the return type of the function. |
| 23 | // It accepts the same type parameters as `Effect.Effect`. |
| 24 | function*(n: number): Effect.fn.Return<string, SomeError> { |
| 25 | yield* Effect.logInfo("Received number:", n) |
| 26 | |
| 27 | // Always return when raising an error, to ensure typescript understands that |
| 28 | // the function will not continue executing. |
| 29 | return yield* new SomeError({ message: "Failed to read the file" }) |
| 30 | }, |
| 31 | // Add additional functionality by passing in additional arguments. |
| 32 | // **Do not** use .pipe with Effect.fn |
| 33 | Effect.catch((error) => Effect.logError(`An error occurred: ${error}`)), |
| 34 | Effect.annotateLogs({ |
| 35 | method: "effectFunction" |
| 36 | }) |
| 37 | ) |
| 38 | |
| 39 | // Effect.fnUntraced avoids tracing and stack-frame capture while still reusing |
| 40 | // the generator body. This is preferred for library functions that do not |
| 41 | // represent a useful tracing boundary. |
| 42 | export const validateBatchSize = Effect.fnUntraced(function*(size: number): Effect.fn.Return<number, SomeError> { |
| 43 | if (!Number.isInteger(size) || size <= 0) { |
| 44 | return yield* new SomeError({ message: "Batch size must be a positive integer" }) |
| 45 | } |
| 46 | return size |
| 47 | }) |
| 48 | |
| 49 | // Use Schema.TaggedError to define a custom error |
| 50 | export class SomeError extends Schema.TaggedError<SomeError>()("SomeError", { |
| 51 | message: Schema.String |
| 52 | }) {} |