@effectionx/context-api

中文文档
0.6.0发布于 2026/04/10MITTypeScriptES Module构建来源已验证近 30 天下载 5.9万

Algebraic effects pattern for context-dependent operations with middleware

原始使用文档
文档目录9 节
  1. Quick Start
  2. Wrapping with Middleware
  3. Min/Max Priority
  4. Instrumentation
  5. Test Mocking
  6. Scope Isolation
  7. API
  8. createApi(name, handler)
  9. around(middlewares, options?)

Context APIs

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 and supports min/max priority ordering.

Quick Start

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

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

export const logging = createApi("logging", {
  *log(...values: unknown[]) {
    console.log(...values);
  },
});

export const { log } = logging.operations;

Now you can use the logging API wherever you want:

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

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

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.

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

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

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:

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

export 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:

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:

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:

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:

M1 → M2 → m1 → m2 → core

Instrumentation

Middleware can be useful for automatic instrumentation:

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);
      }
    },
  });
}

Test Mocking

Mock operations in test cases without changing the call site:

import { fetching } from "./fetching.ts";

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

Scope Isolation

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

import { scoped } from "effection";
import { log, logging } from "./logging.ts";

function* example() {
  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.

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

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

const { add } = math.operations;

function* example(): Operation<void> {
  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
function* example() {
  // 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

版本与发布记录

@effectionx/context-api 共发布 13 个版本,首次发布于 2025/08/07;过去 12 个月发布了 10 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.6.0latest2026/04/107 个月前
0.5.32026/03/307 个月前
0.5.22026/03/237 个月前
0.5.12026/03/217 个月前
0.4.02026/03/138 个月前
0.3.22026/02/248 个月前

关于 @effectionx/context-api 的常见问题

@effectionx/context-api 是什么?

Algebraic effects pattern for context-dependent operations with middleware

如何安装 @effectionx/context-api?

在项目目录运行 npm install @effectionx/context-api,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:effection(^3 || ^4)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@effectionx/context-api 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@effectionx/context-api 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@effectionx/context-api 可以商用吗?

@effectionx/context-api 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@effectionx/context-api 的下载量有多少?

根据 npm 官方下载统计,@effectionx/context-api 在 2026/10/13 – 2026/11/11 这 30 天内被下载 59,235 次,日均约 1,975 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@effectionx/context-api 还在维护吗?

最新版本 0.6.0 发布于 2026/04/10(7 个月前);至今共发布 13 个版本,其中过去 12 个月发布了 10 个;首次发布于 2025/08/07。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。