Skip to content

Resource

Resource: object

Defined in: Core/Resource.ts:31

combine: <E, A, B>(resourceA, resourceB) => Resource<E, readonly [A, B]>

Acquires two resources in sequence and presents them as a tuple. Resources are released in reverse order: the second is released before the first.

If the second resource fails to acquire, the first is released immediately before returning the error.

E

A

B

Resource<E, A>

Resource<E, B>

Resource<E, readonly [A, B]>

const combined = Resource.combine(dbResource, cacheResource);

const result = await pipe(
  combined,
  Resource.use(([conn, cache]) => lookupWithFallback(conn, cache, userId))
)();

from: object

handlers: <E, A>(acquire, release) => Resource<E, A> = makeHandlers

Creates a Resource from an acquire operation that may fail and a release function.

E

A

Result<E, A>

(a) => Task<void>

Resource<E, A>

const fileResource = Resource.from.handlers(
  Task.Result.tryCatch(() => fs.promises.open("data.csv", "r"), { onError: toFileError }),
  (handle) => Task.tryCatch(() => handle.close(), { onError: () => {} })
);

Task: <E, A>(acquire, release) => Resource<E, A> = makeTask

Creates a Resource from an acquire operation that cannot fail. Use this when opening the resource is guaranteed to succeed, such as in-memory locks, counters, or timers.

E

A

Task<A>

(a) => Task<void>

Resource<E, A>

const timerResource = Resource.from.Task<never, Timer>(
  Task.tryCatch(() => Promise.resolve(startTimer()), { onError: () => defaultTimer }),
  (timer) => Task.tryCatch(() => Promise.resolve(timer.stop()), { onError: () => {} })
);

use: <E, A, B>(f) => (resource) => Result<E, B>

Acquires the resource, runs f with it, then releases it.

Release always runs, even when f returns an error. If acquire fails, f and release are both skipped and the error is returned.

E

A

B

(a) => Result<E, B>

(resource) => Result<E, B>

const rows = await pipe(
  dbResource,
  Resource.use((conn) => runQuery(conn, "SELECT * FROM users"))
)();
// conn is closed whether the query succeeds or fails