### Layer Memoization Example Source: https://effect.website/docs/requirements-management/layer-memoization Demonstrates how layers can be composed to create modular and reusable environment setups, including configuring services like databases. ```APIDOC ## POST /api/layers/memoized ### Description This endpoint demonstrates the concept of layer memoization, where a layer is created and potentially reused to provide services efficiently. It shows how to define a service (Database) and provide a live implementation (DatabaseLive) that can be used within an Effect program. ### Method POST ### Endpoint /api/layers/memoized ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (This is a conceptual example demonstrating code structure, not a literal API endpoint with a request body). ### Request Example ```json { "description": "Conceptual example of layer memoization" } ``` ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the successful execution of the conceptual example. - **output** (string) - The console output from running the Effect program. #### Response Example ```json { "message": "Layer memoization example executed successfully.", "output": "timestamp=... level=INFO fiber=#0 message=\"Executing query: SELECT * FROM users\"\n[]" } ``` ``` -------------------------------- ### Console Logging Examples (Node.js) Source: https://effect.website/docs/platform/file-system Provides examples of using the Node.js `console` module for logging. It demonstrates logging to `stdout` and `stderr` using the global `console` object and the `Console` class. Includes examples with string interpolation and error logging. ```javascript const name = 'Will Robinson';console.warn(`Danger ${name}! Danger!`);// Prints: Danger Will Robinson! Danger!, to stderr const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world');// Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened'));// Prints: [Error: Whoops, something bad happened], to err const count = 5; console.log('count: %d', count);// Prints: count: 5, to stdout console.log('count:', count);// Prints: count: 5, to stdout ``` -------------------------------- ### Install @effect/platform Beta Version Source: https://effect.website/docs/platform/introduction Instructions for installing the beta version of the @effect/platform package using various package managers. This includes npm, pnpm, yarn, bun, and deno. ```npm npm install @effect/platform ``` ```pnpm pnpm add @effect/platform ``` ```yarn yarn add @effect/platform ``` ```bun bun add @effect/platform ``` ```deno deno add npm:@effect/platform ``` -------------------------------- ### Install Effect Platform Node Package Source: https://effect.website/docs/platform/introduction Commands to install the @effect/platform-node package using different package managers for Node.js and Deno environments. ```npm npm install @effect/platform-node ``` ```pnpm pnpm add @effect/platform-node ``` ```yarn yarn add @effect/platform-node ``` ```deno deno add npm:@effect/platform-node ``` -------------------------------- ### Node.js Console Logging Examples Source: https://effect.website/docs/error-management/timing-out Demonstrates basic usage of console.log, console.error, and console.warn in Node.js. Includes examples of string formatting and error object logging. Also shows how to create a custom Console instance. ```javascript console.log('hello world');// Prints: hello world, to stdout console.log('%s', 'world');// Prints: world, to stdout console.error(new Error('Whoops, something bad happened'));// Prints error message and stack trace to stderr const name = 'Will Robinson';console.warn(`Danger ${name}! Danger!`);// Prints: Danger Will Robinson! Danger!, to stderr // Example using the Console class: // const out = getStreamSomehow(); // const err = getStreamSomehow(); // const myConsole = new console.Console(out, err); // myConsole.log('hello world');// Prints: hello world, to out // myConsole.warn(`Danger ${name}! Danger!`);// Prints: Danger Will Robinson! Danger!, to err const count = 5; console.log('count: %d', count);// Prints: count: 5, to stdout console.log('count:', count);// Prints: count: 5, to stdout ``` -------------------------------- ### Console Log with Formatting Example (Node.js) Source: https://effect.website/docs/schema/error-messages Provides an example of using console.log with printf-style formatting specifiers in Node.js. It shows how to log numbers and other values using format strings. ```javascript const count = 5;console.log('count: %d', count);// Prints: count: 5, to stdoutconsole.log('count:', count);// Prints: count: 5, to stdout ``` -------------------------------- ### Node.js Console Logging Examples Source: https://effect.website/docs/schema/default-constructors This section provides examples of how to use the Node.js console module for logging. It demonstrates both the global console object and the Console class for writing messages to standard output (stdout) and standard error (stderr). ```javascript // Example using the global console: console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr // Example using the Console class: // Assuming getStreamSomehow() returns a writable stream // const out = getStreamSomehow(); // const err = getStreamSomehow(); // const myConsole = new console.Console(out, err); // myConsole.log('hello world'); // Prints: hello world, to out // myConsole.log('hello %s', 'world'); // Prints: hello world, to out // myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err // myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err // console.Console.log(message?: any, ...optionalParams: any[]): void const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` -------------------------------- ### Effect DateTime: Getting Current Time in a Zone Source: https://effect.website/docs/data-types/datetime Shows how to get the current system time and then apply a specific time zone to it using `Effect.gen` and `DateTime.now`. This example requires importing `Effect` and `DateTime` from the `effect` library. ```typescript import { DateTime, Effect } from "effect" Effect.gen(function* () { const now = yield* DateTime.now const zone = DateTime.zoneUnsafeMakeNamed("Europe/London") // Further operations with 'now' and 'zone' would go here }) ``` -------------------------------- ### Create and Run Hello World with Effect Source: https://effect.website/docs/getting-started/installation A basic example demonstrating how to import Effect modules and execute a program synchronously. ```typescript import { Effect, Console } from "effect" const program = Console.log("Hello, World!") Effect.runSync(program) ``` -------------------------------- ### Effect.interrupt Example Source: https://effect.website/docs/resource-management/scope Shows an example of using Effect.interrupt to explicitly stop a running fiber. The program logs 'start', sleeps, interrupts, and then logs 'done' (which is unreachable). The output demonstrates the interruption in the Exit type. ```typescript import { Effect } from "effect" const program = Effect.gen(function* () { console.log("start") yield* Effect.sleep("2 seconds") yield* Effect.interrupt console.log("done") return "some result" }) Effect.runPromiseExit(program).then(console.log) // Output: // start // { // _id: 'Exit', // _tag: 'Failure', // cause: { // _id: 'Cause', // _tag: 'Interrupt', // fiberId: { // _id: 'FiberId', // _tag: 'Runtime', // id: 0, // startTimeMillis: ... // } // } // } ``` -------------------------------- ### Initialize Project and Install TypeScript Source: https://effect.website/docs/getting-started/installation Commands to create a project directory and initialize a TypeScript environment using various package managers. ```npm mkdir hello-effect cd hello-effect npm init -y npm install --save-dev typescript ``` ```pnpm mkdir hello-effect cd hello-effect pnpm init pnpm add --save-dev typescript ``` ```yarn mkdir hello-effect cd hello-effect yarn init -y yarn add --dev typescript ``` -------------------------------- ### Create and Use Custom Console Instance Source: https://effect.website/docs/observability/metrics This example illustrates creating a custom `Console` instance that directs output to specific streams (e.g., `stdout` and `stderr`). This allows for more granular control over logging destinations compared to the global console object. ```javascript const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world');// Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened'));// Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`);// Prints: Danger Will Robinson! Danger!, to err ``` -------------------------------- ### Concurrent iteration with Effect.forEach Source: https://effect.website/docs/batching An example of performing concurrent operations on a list of items, such as sending notifications for a list of todos, using the concurrency option. ```typescript Effect.forEach(todos, (todo) => notifyOwner(todo), { concurrency: "unbounded" }); ``` -------------------------------- ### Custom Console Logging Example Source: https://effect.website/docs/concurrency/fibers Shows how to create a custom Console instance that directs output to specific streams (e.g., stdout and stderr). This allows for more controlled logging compared to the global console object. The example assumes functions `getStreamSomehow()` exist to provide writable streams. ```javascript // Assuming getStreamSomehow() returns appropriate writable streams // const out = getStreamSomehow(); // const err = getStreamSomehow(); // const myConsole = new console.Console(out, err); // myConsole.log('hello world'); // myConsole.log('hello %s', 'world'); // myConsole.error(new Error('Whoops, something bad happened')); ``` -------------------------------- ### Run Effect as a Promise (Success) Source: https://effect.website/docs/ai/planning-llm-interactions This example shows how to execute an Effect that succeeds and get its result as a JavaScript Promise. It's useful for integrating Effect-TS with existing promise-based code. ```typescript import { Effect } from "effect" Effect.runPromise(Effect.succeed(1)).then(console.log) // Output: 1 ``` -------------------------------- ### Custom Console Instance Source: https://effect.website/docs/additional-resources/effect-vs-promise Illustrates creating and using a custom Console instance with specific output streams. ```APIDOC ## Custom Console Instance ### Description Creates a custom `Console` instance that writes to specified output and error streams. ### Method `new console.Console(stdout[, stderr][, ignoreErrors])` ### Endpoint N/A (Class constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); myConsole.error(new Error('Whoops, something bad happened')); ``` ### Response #### Success Response (200) N/A #### Response Example ``` // 'hello world' is written to 'out' // '[Error: Whoops, something bad happened]' is written to 'err' ``` ``` -------------------------------- ### Fetch Data with tryPromise Source: https://effect.website/docs/batching Examples showing basic usage of tryPromise for fetching data, including default error handling and custom error mapping. ```typescript import { Effect } from "effect"; // Basic usage with UnknownException const getTodo = (id: number) => Effect.tryPromise(() => fetch(`https://jsonplaceholder.typicode.com/todos/${id}`) ); // Usage with custom error handling const getTodoCustom = (id: number) => Effect.tryPromise({ try: () => fetch(`https://jsonplaceholder.typicode.com/todos/${id}`), catch: (unknown) => new Error(`something went wrong ${unknown}`) }); ``` -------------------------------- ### Running a Schedule with Inputs Source: https://effect.website/docs/scheduling/built-in-schedules This example demonstrates how to use `Schedule.run` to execute a schedule with a given set of inputs and a starting timestamp. It collects all the outputs produced by the schedule. ```typescript import * as Schedule from "effect/Schedule" import * as Duration from "effect/Duration" import * as Chunk from "effect/Chunk" // Assuming 'schedule' is a defined Schedule // and 'now' is a number representing the start time. // const run: (self: Schedule.Schedule, now: number, input: Iterable) => Effect.Effect, never, never> // Example usage (requires a concrete schedule definition): // const mySchedule = Schedule.recurs(10); // const program = Schedule.run(mySchedule, Date.now(), [1, 2, 3]); // Effect.runPromise(program).then(outputs => console.log(outputs)); ``` -------------------------------- ### Initialize and Run Effect with Bun Source: https://effect.website/docs/getting-started/installation Steps to set up a Bun project with strict TypeScript configuration, install the Effect package, and execute the application. Ensures the environment is ready for Effect development. ```bash mkdir hello-effect cd hello-effect bun init bun add effect ``` ```json { "compilerOptions": { "strict": true } } ``` ```typescript import { Effect, Console } from "effect" const program = Console.log("Hello, World!") Effect.runSync(program) ``` ```bash bun index.ts ``` -------------------------------- ### Initialize and Run Effect with Deno Source: https://effect.website/docs/getting-started/installation Commands to initialize a Deno project, add the Effect dependency, and execute a main.ts file. Requires the Deno runtime installed on the system. ```bash mkdir hello-effect cd hello-effect deno init deno add npm:effect ``` ```typescript import { Effect, Console } from "effect" const program = Console.log("Hello, World!") Effect.runSync(program) ``` ```bash deno run main.ts ``` -------------------------------- ### Log Messages with Node.js Console Source: https://effect.website/docs/error-management/retrying Examples of using the global console object for logging, warnings, and error reporting, as well as instantiating a custom Console class for specific output streams. ```javascript console.log('hello world'); console.error(new Error('Whoops, something bad happened')); const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Custom Console instance const myConsole = new console.Console(process.stdout, process.stderr); myConsole.log('hello world'); ``` -------------------------------- ### Fetching Todos with AbortSignal and Custom Error (TypeScript) Source: https://effect.website/docs/batching Illustrates using Effect.tryPromise with an AbortSignal for interruption and a custom error type `GetTodosError`. This example also shows integration with HttpService. ```typescript import { Effect } from "effect" import { HttpService } from "@effect/platform" import { RequestResolver } from "@effect/platform" // Assume GetTodos and GetTodosError are defined elsewhere // interface GetTodos {} // class GetTodosError {} const getTodosResolver = Effect.tryPromise({ try: (signal: AbortSignal) => // Assuming fetch is available and returns a Promise fetch("https://api.example.demo/todos", { signal }) .then((res: Response) => res.json() as Promise>), // Replace 'any' with your Todo type catch: (error: unknown) => new GetTodosError() }) const GetTodosResolver: Effect.Effect, never, HttpService> = getTodosResolver.pipe( RequestResolver.contextFromServices(HttpService) ) // Example usage within a query definition (assuming GetTodos is a Request type) // const getTodos: Effect.Effect = Effect.request(GetTodos({}), GetTodosResolver) ``` -------------------------------- ### Fetch Data with Effect.tryPromise Source: https://effect.website/docs/batching Examples showing the two primary ways to use tryPromise: a simple version that defaults to UnknownException, and a version with a custom catch function to map errors. ```typescript // Basic usage const getTodo = (id: number) => Effect.tryPromise(() => fetch(`https://jsonplaceholder.typicode.com/todos/${id}`) ); // Custom error handling const getTodoCustom = (id: number) => Effect.tryPromise({ try: () => fetch(`https://jsonplaceholder.typicode.com/todos/${id}`), catch: (unknown) => new Error(`something went wrong ${unknown}`) }); ``` -------------------------------- ### Node.js Console Class Example (JavaScript) Source: https://effect.website/docs/additional-resources/effect-vs-promise Demonstrates creating a custom Console instance in Node.js by providing specific streams for output and error. This allows for more controlled logging to different destinations. Methods include log, error, and warn. ```javascript const out = getStreamSomehow();const err = getStreamSomehow();const myConsole = new console.Console(out, err); myConsole.log('hello world');// Prints: hello world, to outmyConsole.log('hello %s', 'world');// Prints: hello world, to outmyConsole.error(new Error('Whoops, something bad happened'));// Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson';myConsole.warn(`Danger ${name}! Danger!`);// Prints: Danger Will Robinson! Danger!, to err ``` -------------------------------- ### Running an Effect as a Promise (Success) Source: https://effect.website/docs/resource-management/introduction This example shows how to execute an Effect that succeeds and get its result as a JavaScript Promise. The `runPromise` function resolves the Promise with the effect's successful value. ```typescript import { Effect } from "effect"; Effect.runPromise(Effect.succeed(1)).then(console.log); // Output: 1 ``` -------------------------------- ### Initialize Effect DevTools Source: https://effect.website/docs/getting-started/devtools Example demonstrating how to import the DevTools module and provide it as a layer to an Effect application. This enables the real-time tracer and metrics view. ```typescript import { DevTools } from "@effect/experimental" import { NodeRuntime, NodeSocket } from "@effect/platform-node" import { Effect, Layer } from "effect" const program = Effect.log("Hello!").pipe( Effect.delay(2000), Effect.withSpan("Hi", { attributes: { foo: "bar" } }), Effect.forever, ) const DevToolsLive = DevTools.layer() program.pipe(Effect.provide(DevToolsLive), NodeRuntime.runMain) ``` -------------------------------- ### Instantiating Custom Console Class Source: https://effect.website/docs/schema/error-messages Shows how to create a custom Console instance by providing specific output and error streams, allowing for redirected logging. ```javascript const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); myConsole.log('hello %s', 'world'); myConsole.error(new Error('Whoops, something bad happened')); ``` -------------------------------- ### Console Logging (JavaScript) Source: https://effect.website/docs/error-management/retrying Provides examples of using the global `console` object in Node.js for logging messages to standard output and standard error. It covers basic logging, formatted strings, and error object logging. ```javascript const name = 'Will Robinson'; console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` -------------------------------- ### Define and Extract Service Type with Context.Tag Source: https://effect.website/docs/requirements-management/services This example shows how to define a service using `Context.Tag` and then extract its type definition. It includes a `Random` service with a `next` operation and demonstrates how to get the shape of this service. ```typescript import { Effect, Context } from "effect" class RandomRandom extends Context.Tag("MyRandomService")< RandomRandom, { readonly next: Effect.Effect }>() {} type RandomShape = { readonly next: Effect.Effect; } ``` -------------------------------- ### Cache Lookup with Effect.all (Effect-TS) Source: https://effect.website/docs/caching/cache Shows how Effect.all can be used with a cache to retrieve values. It attempts to get values for specified keys, computing and caching them if they don't exist. This example assumes a pre-configured cache. Requires the 'effect' library. ```typescript import * as Effect from "effect"; import * as Cache from "effect/Cache"; // Assume 'cache' is a pre-configured Cache.Cache // const cache: Cache.Cache = ...; // Example of getting from cache, computing if absent // cache.get("key1") // Effect.Effect // Effect.all can be used to get multiple values from the cache concurrently. // Effect.all([ // cache.get("key1"), // cache.get("key1"), // cache.get("key1") // ], { // concurrency: "unbounded" // }); ``` -------------------------------- ### Create a custom Console instance Source: https://effect.website/docs/data-types/datetime Shows how to create a custom `Console` instance in Node.js, directing output to specific streams (e.g., stdout and stderr). This allows for more controlled logging, separating messages to different destinations. ```javascript const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); myConsole.error(new Error('Whoops, something bad happened')); const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); ``` -------------------------------- ### Send Email to User with Effect Source: https://effect.website/docs/batching Sends an email to a user after fetching their details. It chains the effect of getting a user by ID with the effect of sending an email. Dependencies include `Effect` and potentially `GetUserError` and `SendEmailError`. ```typescript const sendEmailToUser = (id: number, message: string): Effect.Effect => getUserById(id).pipe( Effect.andThen((user) => sendEmail(user.email, message)) ); ``` -------------------------------- ### Chaining Effects with Effect.andThen Source: https://effect.website/docs/batching Shows an alternative way to chain Effects using `Effect.andThen`. This method achieves the same result as `Effect.map` followed by `Effect.flatMap` in the previous example, demonstrating a more concise syntax for sequential Effect execution. ```typescript // Using Effect.andThen const result2 = pipe( fetchTransactionAmount, Effect.andThen((amount) => amount * 2), Effect.andThen((amount) => applyDiscount(amount, 5)) ) Effect.runPromise(result2).then(console.log)// Output: 190 ``` -------------------------------- ### Using the Console Class in Node.js Source: https://effect.website/docs/schema/default-constructors Shows how to create and use a custom Console instance by providing specific output and error streams. This allows for more controlled logging to different destinations. ```javascript const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); const name = 'Will Robinson'; myConsole.log('hello world'); myConsole.log('hello %s', 'world'); myConsole.error(new Error('Whoops, something bad happened')); myConsole.warn(`Danger ${name}! Danger!`); ``` -------------------------------- ### Chaining Effects with Effect.map and Effect.flatMap Source: https://effect.website/docs/batching Illustrates chaining asynchronous operations using `Effect.map` and `Effect.flatMap`. This example fetches a transaction amount, doubles it, and then applies a discount. The result is an Effect that, when run, produces the final calculated value. ```typescript // Using Effect.map and Effect.flatMap const result1 = pipe( fetchTransactionAmount, Effect.map((amount) => amount * 2), Effect.flatMap((amount) => applyDiscount(amount, 5)) ) Effect.runPromise(result1).then(console.log)// Output: 190 ``` -------------------------------- ### Running an Effect and Getting Exit Result as Promise Source: https://effect.website/docs/getting-started/control-flow This example demonstrates how to execute a simple successful effect using Effect.runPromiseExit and then handle the resulting Promise, which resolves to an 'Exit' object. The 'Exit' object clearly indicates success and the value produced. ```typescript import { Effect } from "effect" Effect.runPromiseExit(Effect.succeed(1)).then(console.log) ``` -------------------------------- ### Applying Discounts with Effect.andThen Source: https://effect.website/docs/getting-started/building-pipelines A practical example showing how to fetch data and apply transformations using Effect.andThen, compared against the traditional map and flatMap approach. ```typescript import { pipe, Effect } from "effect"; const applyDiscount = (total: number, discountRate: number): Effect.Effect => discountRate === 0 ? Effect.fail(new Error("Discount rate cannot be zero")) : Effect.succeed(total - (total * discountRate) / 100); const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)); // Using Effect.andThen const result = pipe( fetchTransactionAmount, Effect.andThen((amount) => amount * 2), Effect.andThen((amount) => applyDiscount(amount, 5)) ); Effect.runPromise(result).then(console.log); // Output: 190 ``` -------------------------------- ### Measuring Elapsed Time with Effect.gen Source: https://effect.website/docs/code-style/do Provides an example of using `Effect.gen` from the 'effect' library to measure the time taken for an asynchronous operation. It utilizes `Effect.sync` to get the current time and demonstrates a common pattern for performance measurement in functional programming. ```typescript import { Effect } from "effect" // Get the current timestamp const now: Effect.Effect = Effect.sync(() => new Date().getTime()) // Measure elapsed time for an effect const elapsed = (self: Effect.Effect): Effect.Effect => Effect.flatMap(now, (start) => Effect.map(self, (result) => { const end = new Date().getTime() console.log(`Elapsed: ${end - start}ms`) return result }) ) // Example usage: const task = Effect.sync(() => { // Simulate some work let sum = 0; for (let i = 0; i < 1000000; i++) { sum += i; } console.log('some task'); }); const program = elapsed(task) Effect.runPromise(program) ``` -------------------------------- ### Utilize Node.js Console for Debugging Source: https://effect.website/docs/data-types/hash-set Explains how to use the global console instance for standard output and how to instantiate a custom Console class to direct logs to specific streams. ```javascript const name = 'Will Robinson'; // Global console usage console.log('hello %s', 'world'); console.warn(`Danger ${name}! Danger!`); // Custom Console class usage const myConsole = new console.Console(process.stdout, process.stderr); myConsole.log('Custom stream output'); myConsole.error(new Error('Something went wrong')); ``` -------------------------------- ### Generate Incrementing Numbers Stream with Stream.iterate Source: https://effect.website/docs/stream/creating This example demonstrates how to create an infinite stream of incrementing numbers starting from 1 using Stream.iterate. The stream is then limited to the first 10 elements and collected into a chunk for display. This showcases the core functionality of generating sequences iteratively. ```typescript import { Effect, Stream } from "effect" // An infinite Stream of numbers starting from 1 and incrementing const stream = Stream.iterate(1, (n) => n + 1) Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(10)))).then(console.log) // Expected output: { _id: 'Chunk', values: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] } ``` -------------------------------- ### Capture Interruption Details with Effect.js Source: https://effect.website/docs/concurrency/basic-concurrency Demonstrates how to capture interruption details like fiber ID and start time using Effect.js. The resulting interruption can be observed in the Exit type when the effect is run with `runPromiseExit`. This example shows a program that sleeps, interrupts, and then logs 'done'. ```typescript import { Effect } from "effect" const program = Effect.gen(function* () { console.log("start") yield* Effect.sleep("2 seconds") yield* Effect.interrupt console.log("done") return "some result" }) Effect.runPromiseExit(program).then(console.log) ``` -------------------------------- ### Install Effect Dependency Source: https://effect.website/docs/getting-started/installation Commands to add the Effect library to your project dependencies. ```npm npm install effect ``` ```pnpm pnpm add effect ``` ```yarn yarn add effect ``` -------------------------------- ### Retrying a Failing Effect with Effect.retry and Schedule Source: https://effect.website/docs/error-management/retrying Demonstrates how to automatically retry an Effect if it fails, using a specified retry policy. This is essential for handling transient errors like network issues. The example shows retrying with a fixed delay and retrying a specific number of times. ```javascript import { Effect, Schedule } from "effect" let count = 0 // Simulates an effect with possible failuresconst task = Effect.async((resume) => { if (count <= 2) { count++ console.log("failure") resume(Effect.fail(new Error())) } else { console.log("success") resume(Effect.succeed("yay!")) }}) // Define a repetition policy using a fixed delay between retriesconst policy = Schedule.fixed("100 millis") const repeated = Effect.retry(task, policy) Effect.runPromise(repeated).then(console.log)// Output:// failure// failure// failure// success// yay! ``` ```javascript import { Effect } from "effect" let count = 0 // Simulates an effect with possible failuresconst task = Effect.async((resume) => { if (count <= 2) { count++ console.log("failure") resume(Effect.fail(new Error())) } else { console.log("success") resume(Effect.succeed("yay!")) }}) // Retry the task up to 5 timesEffect.runPromise(Effect.retry(task, { times: 5 })).then(console.log)// Output:// failure// failure// failure// success ``` -------------------------------- ### Console Logging Examples Source: https://effect.website/docs/error-management/matching Demonstrates various ways to use the console object for logging messages and errors. Includes basic console.warn, creating a custom Console instance with specific output streams, and using printf-style formatting. ```javascript const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` ```javascript const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ``` ```javascript const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` -------------------------------- ### Effect.andThen for Sequential Effectful Operations Source: https://effect.website/docs/batching Demonstrates the use of Effect.andThen for chaining sequential operations where subsequent operations depend on the results of preceding ones. This example shows fetching a user and then sending them an email notification, handling potential errors from both fetching and sending. ```typescript import { pipe, Effect } from "effect" // Assume User, Todo, GetUserError, SendEmailError types and functions getUserById, sendEmail are defined elsewhere. // interface User { id: number; name: string; email: string; } // interface Todo { id: number; ownerId: number; } // declare const getUserById: (id: number) => Effect.Effect; // declare const sendEmail: (address: string, text: string) => Effect.Effect; // Uses getUserById to fetch the owner of a Todo and then sends them an email notification const notifyOwner = (todo: { ownerId: number }): Effect.Effect => getUserById(todo.ownerId).pipe( Effect.andThen((user) => sendEmail(user.email, `hey ${user.name} you got a todo!`)) ) ``` -------------------------------- ### Custom Console Logging Example Source: https://effect.website/docs/data-types/cause Shows how to create and use a custom `Console` instance with specific output and error streams, providing more control over logging destinations. ```javascript const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world') myConsole.log('hello %s', 'world') myConsole.error(new Error('Whoops, something bad happened')) ``` -------------------------------- ### Retry Stream with Exponential Backoff in TypeScript Source: https://effect.website/docs/stream/error-handling Retries an entire stream according to a specified schedule, re-executing all acquire operations. The schedule resets upon the first element passing through the stream. This example uses an exponential backoff schedule starting with a 1-second base delay. ```typescript Stream.retry(Schedule.exponential("1 second")) ``` -------------------------------- ### Create and use a custom Console instance Source: https://effect.website/docs/code-style/pattern-matching Illustrates how to create a custom Console instance by providing specific output and error streams. This allows for more controlled logging to different destinations. The custom instance supports methods like log, error, and warn. ```javascript const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); myConsole.error(new Error('Whoops, something bad happened')); const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); ``` -------------------------------- ### Create a Matcher Source: https://effect.website/docs/code-style/pattern-matching Demonstrates how to initialize a Matcher using either type-based or value-based matching. These methods serve as the entry point for defining pattern matching logic. ```typescript import { Match } from "effect"; // Match against a specific type const typeMatcher = Match.type(); // Match against a specific value const valueMatcher = Match.value(10); ``` -------------------------------- ### Chaining Effects with andThen in Effect.js Source: https://effect.website/docs/batching Illustrates chaining effects using `Effect.andThen` in Effect.js. Similar to the `map`/`flatMap` example, this demonstrates sequencing operations where the output of one effect is passed to the next. `andThen` is a more concise way to express sequential effect composition. ```typescript const result2 = pipe( fetchTransactionAmount, Effect.andThen((amount) => amount * 2), Effect.andThen((amount) => applyDiscount(amount, 5)) ) Effect.runPromise(result2).then(console.log)// Output: 190 ``` -------------------------------- ### Utilize Node.js Console Source: https://effect.website/docs/error-management/retrying Shows how to use the global console for standard output and error logging, as well as how to instantiate a custom Console class to direct output to specific streams. ```javascript // Using the global console console.log('hello %s', 'world'); console.error(new Error('Whoops, something bad happened')); // Using the Console class with custom streams const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); ``` -------------------------------- ### Retrieve First Element from Stream using Sink.head (TypeScript) Source: https://effect.website/docs/sink/creating This example demonstrates how to use `Sink.head` to get the first element from a `Stream`. It imports necessary components from 'effect' and uses `Effect.runPromise` to execute the stream operation. The output will be `Some(1)` if the stream is non-empty, or `None` if it's empty. ```typescript import { Effect, Stream, Sink } from "effect" const nonEmptyStream: Stream.Stream = Stream.make(1, 2, 3, 4) Effect.runPromise(Stream.run(nonEmptyStream, Sink.head())).then(console.log) // Expected output: Some(1) ``` -------------------------------- ### Logging with Console API in Node.js Source: https://effect.website/docs/schema/transformations Demonstrates how to use the global console object for warnings and logs, as well as how to instantiate a custom Console class with specific output and error streams. ```javascript const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); myConsole.log('hello %s', 'world'); myConsole.error(new Error('Whoops, something bad happened')); const count = 5; console.log('count: %d', count); console.log('count:', count); ``` -------------------------------- ### Processing Iterable Elements with Effect.forEach (TypeScript) Source: https://effect.website/docs/batching Applies an effectful operation to each element of an iterable using `Effect.forEach` in Effect.js. This example logs the current index and doubles the element's value, collecting the results. It demonstrates handling effects within loops and managing concurrency. ```typescript import { Effect, Console } from "effect" const result = Effect.forEach([1, 2, 3, 4, 5], (n, index) => Console.log(`Currently at index ${index}`).pipe(Effect.as(n * 2)) ) Effect.runPromise(result).then(console.log)// Output:// Currently at index 0// Currently at index 1// Currently at index 2// Currently at index 3// Currently at index 4// [ 2, 4, 6, 8, 10 ] ``` -------------------------------- ### Handle Timeout with Custom Error using Effect.timeoutFail Source: https://effect.website/docs/error-management/timing-out This snippet shows how to use Effect.timeoutFail to return a specific error when an effect times out. It is demonstrated within an Effect.gen block, which simplifies asynchronous code by allowing generator functions. The example logs a 'Start processing...' message and then attempts to sleep, which would be interrupted by a timeout if configured. ```typescript import { Effect, Data } from "effect" const task: Effect.Effect = Effect.gen(function* () { console.log("Start processing...") yield* Effect.sleep(1000) return "Task completed" }) // Example usage of timeoutFail would typically wrap 'task' like: // Effect.timeoutFail(task, 500).pipe( // Effect.catchTag("Timeout") // Assuming Timeout is the error tag // => Effect.succeed("Operation timed out!") // ) ``` -------------------------------- ### Basic Console Logging Source: https://effect.website/docs/additional-resources/effect-vs-promise Demonstrates basic logging of strings and formatted strings to standard output. ```APIDOC ## Console Logging ### Description Logs messages to the console. Supports string interpolation. ### Method `console.log(message?: any, ...optionalParams: any[]): void` ### Endpoint N/A (Global object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript console.log('hello world'); console.log('hello %s', 'world'); ``` ### Response #### Success Response (200) N/A #### Response Example ``` hello world hello world ``` ``` -------------------------------- ### Create Readline Interface and Prompt User Source: https://effect.website/docs/state-management/ref Demonstrates initializing a Node.js readline interface using standard input and output streams. It includes an example of using the question method to capture user input asynchronously. ```typescript import readline from 'node:readline'; const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('What is your favorite food? ', (answer) => { console.log(`Oh, so your favorite food is ${answer}`); rl.close(); }); ``` -------------------------------- ### Effect.andThen with User Data and Email Sending Source: https://effect.website/docs/batching An example demonstrating the use of `Effect.andThen` with user data. It shows how to process a user object and then trigger an action, such as sending an email, within an Effect chain. This highlights `andThen`'s capability to handle sequential asynchronous operations involving complex data types. ```typescript @since ― 2.0.0 andThen((user: User) => const sendEmailToUser: (id: number, message: string) => Effect.Effect sendEmailToUser(user.id, `hey ${user.name} you got a todo!`) ) ) ) ``` -------------------------------- ### Scaffold Vite + React Project Source: https://effect.website/docs/getting-started/installation Commands to initialize a new Vite project with the React-TypeScript template across various package managers. ```bash npm create vite@latest hello-effect -- --template react-ts ``` ```bash pnpm create vite@latest hello-effect -- --template react-ts ``` ```bash yarn create vite@latest hello-effect -- --template react-ts ``` ```bash bun create vite@latest hello-effect -- --template react-ts ``` ```bash deno init --npm vite@latest hello-effect -- --template react-ts ```