Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,18 @@
"indentStyle": "space",
"indentWidth": 2
},
"overrides": [
{
"include": ["context-api/mod.ts"],
"linter": {
"rules": {
"suspicious": {
"noExplicitAny": "off"
}
}
}
}
],
"files": {
"ignore": ["**/dist", "**/node_modules", "**/build"]
}
Expand Down
235 changes: 196 additions & 39 deletions context-api/README.md
Original file line number Diff line number Diff line change
@@ -1,94 +1,251 @@
# Context Apis
# Context APIs

Often called "Algebraic Effects" or "Contextual Effects", Context apis let you
access an operation via the context in a way that it can be easily (and
contextually) wrapped with middleware.
Algebraic effects pattern for context-dependent operations with middleware

---

Often called "Algebraic Effects" or "Contextual Effects", Context APIs let you
access an operation via the context in a way that it can be easily (and
contextually) wrapped with middleware. Middleware is powered by
[`@effectionx/middleware`](../middleware/README.md) and supports min/max priority
ordering.

## Quick Start

Let's say that you want to define a log operation that behaves differently in
different context. The basic form will just log values to the console.
different contexts. The basic form will just log values to the console.

```ts
// file logging.ts
import { createApi } from "@effectionx/context-api";

// create the `logging` api. By default, it just logs to the console.
const logging = createApi<Logging>(
"logging",
function* log(...values: unknown[]) {
const logging = createApi("logging", {
*log(...values: unknown[]) {
console.log(...values);
},
);
});

// export the logging operations.
export const { log } = logging.operations;
```

Now you can use the logging api wherever you want:
Now you can use the logging API wherever you want:

```ts
import { log } from "./logging.ts";

export function* op() {
yield* log(`I am in an operation`);
yield* log("I am in an operation");
}
```

However, use can use the `around` function to wrap middleware around your
logging operation. This lets you do stuff like silence logging, or even to
re-route it somewhere else than from the `console` completely.
## Wrapping with Middleware

Use the `around` function to wrap middleware around your operations. This lets
you intercept calls, transform arguments, modify return values, or replace
the implementation entirely.

```ts
import { logging } from "./logging.ts";

function* initCustomLogging(externallogger) {
function* initCustomLogging(externalLogger) {
yield* logging.around({
*log(...values, next) {
*log([...values], next) {
externalLogger.log(...values);
// since we override the logger entirely, we do not invoke next.
// since we override the logger entirely, we do not invoke next
},
});
}
```

The best part is that the middleware is only in effect inside the scope in which
it is installed.
Middleware is only in effect inside the scope in which it is installed — when
the scope exits, the middleware is removed.

## Min/Max Priority

By default, `around()` registers middleware at `"max"` priority (outermost,
closest to the caller). You can also register at `"min"` priority (innermost,
closest to the core handler) by passing an options argument:

```ts
import { createApi } from "@effectionx/context-api";
import type { Operation } from "effection";

const files = createApi("files", {
*readFile(path: string): Operation<string> {
throw new Error(`readFile("${path}") is not implemented`);
},
});

export const { readFile } = files.operations;
```

In your runtime setup, provide the implementation via `min`:

```ts
import { files } from "./files.ts";

function* initNodeRuntime() {
yield* files.around(
{
*readFile([path], _next) {
return yield* nodeReadFile(path);
},
},
{ at: "min" },
);
}
```

`max` middlewares wrap the outside as usual — they don't care which `min` is
providing the actual implementation:

```ts
import { files } from "./files.ts";

function* withLogging() {
yield* files.around({
*readFile([path], next) {
console.log(`reading ${path}`);
return yield* next(path);
},
});
}
```

In tests, swap the implementation by registering a different `min`:

```ts
function* useTestFixtures(fixtures: Map<string, string>) {
yield* files.around(
{
*readFile([path], _next) {
return fixtures.get(path) ?? "";
},
},
{ at: "min" },
);
}
```

The execution order with max middlewares `[M1, M2]` and min middlewares
`[m1, m2]` is:

```text
M1 → M2 → m1 → m2 → core
```

## Instrumentation

Middleware can be useful for automatic instrumentation. For example, let's
assume that `fetch` was a an api called `fetching`:
Middleware can be useful for automatic instrumentation:

```ts
import { fetch, fetching } from "./fetching.ts";
import { fetching } from "./fetching.ts";

function* instrumentFetch(tracer) {
yield* fetching.around({
*fetch(...args, next) {
try {
tracer.begin("fetch", args),
return yield* next(...args);
} finally {
tracer.end("fetch", args);
}
}
})
*fetch(args, next) {
try {
tracer.begin("fetch", args);
return yield* next(...args);
} finally {
tracer.end("fetch", args);
}
},
});
}
```

or mocking inside test cases:
## Test Mocking

Mock operations in test cases without changing the call site:

```ts
import { fetch, fetching } from "./fetching.ts";
import { fetching } from "./fetching.ts";

function* useMocks() {
yield* fetching.around({
*fetch(...args, next) {
if (args[0] === "/my-path") {
*fetch([url, ...rest], next) {
if (url === "/my-path") {
return new MockResponse("my-path");
} else {
return yield* next(...args);
return yield* next(url, ...rest);
}
},
});
}
```

## Scope Isolation

Middleware installed in a child scope does not affect the parent:

```ts
import { scoped } from "effection";

yield* scoped(function* () {
yield* logging.around({
*log([...values], next) {
// only active inside this scope
return yield* next(...values);
},
});
yield* log("intercepted"); // middleware runs
});

yield* log("not intercepted"); // middleware does not run
```

## API

### `createApi(name, handler)`

Create a context API from a name and an object of handler functions or
operations. Returns an object with `operations` and `around`.

```ts
import { createApi } from "@effectionx/context-api";

const math = createApi("math", {
*add(left: number, right: number): Operation<number> {
return left + right;
},
});

const { add } = math.operations;
const result = yield* add(1, 2); // => 3
```

### `around(middlewares, options?)`

Register middleware around one or more operations. The second argument controls
priority:

- **`{ at: "max" }`** (default) — outermost, closest to the caller
- **`{ at: "min" }`** — innermost, closest to the core handler

```ts
// Wrapping middleware (max, default)
yield* math.around({
*add(args, next) {
console.log("adding", args);
return yield* next(...args);
},
});

// Implementation middleware (min)
yield* math.around(
{
*add([left, right], _next) {
return left * right; // replace the core implementation
},
},
{ at: "min" },
);
```

Each middleware receives the arguments as a tuple and a `next` function to
delegate to the next middleware (or the core handler). A middleware can:

- **Pass through**: call `next(...args)` and return its result
- **Transform arguments**: call `next()` with different arguments
- **Transform the return value**: modify what `next()` returns
- **Short-circuit**: return a value without calling `next()` at all
Loading
Loading