DEV Community

Alex Spinov
Alex Spinov

Posted on

Effect Has a Free API You Should Know About

Effect is a TypeScript library that gives you superpowers for building reliable, composable applications.

The Core Effect API

import { Effect, pipe } from 'effect'

const fetchUser = (id: string) =>
  Effect.tryPromise({
    try: () => fetch(`/api/users/${id}`).then(r => r.json()),
    catch: () => new Error(`Failed to fetch user ${id}`)
  })

const program = pipe(
  fetchUser('123'),
  Effect.map(user => `Hello, ${user.name}!`),
  Effect.tap(greeting => Effect.log(greeting))
)
await Effect.runPromise(program)
Enter fullscreen mode Exit fullscreen mode

Built-in Retry and Timeout

import { Effect, Schedule, Duration } from 'effect'

const resilientFetch = pipe(
  fetchUser('123'),
  Effect.retry(
    Schedule.exponential(Duration.seconds(1)).pipe(
      Schedule.compose(Schedule.recurs(3))
    )
  ),
  Effect.timeout(Duration.seconds(10))
)
Enter fullscreen mode Exit fullscreen mode

Structured Concurrency

const fetchAll = Effect.all([
  fetchUser('1'), fetchUser('2'), fetchUser('3')
], { concurrency: 3 })

const fastest = Effect.race(
  fetchFromCache('key'), fetchFromDB('key')
)
Enter fullscreen mode Exit fullscreen mode

Schema — Runtime Validation

import { Schema } from 'effect'

const User = Schema.Struct({
  id: Schema.String,
  name: Schema.String,
  email: Schema.String.pipe(Schema.pattern(/^.+@.+\..+$/)),
  age: Schema.Number.pipe(Schema.between(0, 150))
})
type User = Schema.Schema.Type<typeof User>
Enter fullscreen mode Exit fullscreen mode

Real-World Use Case

A fintech startup had a payment pipeline with 15 try-catch blocks and manual retries. They rewrote it with Effect: typed errors, automatic retries with backoff, structured logging. Code went from 400 lines to 120, catching 3 edge cases their try-catch missed.

Effect is what TypeScript error handling should have been from day one.


Build Smarter Data Pipelines

Need to scrape websites, extract APIs, or automate data collection? Check out my ready-to-use scrapers on Apify — no coding required.

Custom scraping solution? Email me at spinov001@gmail.com — fast turnaround, fair prices.

Top comments (0)