块编辑器开发文档

@wordpress/redux-routine

💡 云策文档标注

概述

@wordpress/redux-routine 是一个用于 Redux 的中间件,基于 JavaScript 的生成器(Generators)和 Promise 实现协程,以处理异步或条件性操作流。它通过定义控制处理器(control handlers)来管理 action 的执行,适用于需要简化异步流程的 WordPress 开发场景。

关键要点

  • 安装方式:通过 npm 安装,需注意对旧浏览器(如 IE 11)提供 polyfills。
  • 核心功能:默认导出一个函数,接收 controls 对象并返回 Redux 中间件,用于处理特定 action 类型的异步操作。
  • 使用示例:定义生成器函数(如 retrieveTemperature)来 yield action,控制处理器(如 FETCH_JSON)执行网络请求,完成后继续执行并返回新 action。
  • API 说明:createMiddleware 函数参数为 controls 对象,键为 action 类型,值为返回 Promise 或值的函数,控制执行流程。
  • 动机:相比 redux-saga 等方案更轻量,无默认控制或错误处理,强调可测试性、灵活性和团队协作的领域语言。
  • 测试方法:生成器函数返回可迭代的 action 对象,易于通过 assert 等工具进行单元测试。
  • 贡献信息:作为 Gutenberg 项目的一部分,采用 monorepo 结构,鼓励社区贡献。

代码示例

import createMiddleware from '@wordpress/redux-routine';

const middleware = createMiddleware( {
    async FETCH_JSON( action ) {
        const response = await window.fetch( action.url );
        return response.json();
    },
} );

function* retrieveTemperature() {
    const result = yield { type: 'FETCH_JSON', url: 'https://' };
    return { type: 'SET_TEMPERATURE', temperature: result.value };
}

注意事项

  • 需支持旧浏览器时,自行提供 Promise 和 Generators 的 polyfills。
  • 控制处理器返回 undefined 会停止执行,需确保正确处理返回值以继续流程。
  • 该中间件不包含默认错误处理,开发者需自行实现异常管理。

📄 原文内容

Redux middleware for generator coroutines.

Installation

Install Node if you do not already have it available.

Install the module to your project using npm:

npm install @wordpress/redux-routine

@wordpress/redux-routine leverages both Promises and Generators, two modern features of the JavaScript language. If you need to support older browsers (Internet Explorer 11 or earlier), you will need to provide your own polyfills.

Usage

The default export of @wordpress/redux-routine is a function which, given an object of control handlers, returns a Redux middleware function.

For example, consider a common case where we need to issue a network request. We can define the network request as a control handler when creating our middleware.

import { combineReducers, createStore, applyMiddleware } from 'redux';
import createMiddleware from '@wordpress/redux-routine';

const middleware = createMiddleware( {
    async FETCH_JSON( action ) {
        const response = await window.fetch( action.url );
        return response.json();
    },
} );

function temperature( state = null, action ) {
    switch ( action.type ) {
        case 'SET_TEMPERATURE':
            return action.temperature;
    }

    return state;
}

const reducer = combineReducers( { temperature } );

const store = createStore( reducer, applyMiddleware( middleware ) );

function* retrieveTemperature() {
    const result = yield { type: 'FETCH_JSON', url: 'https://' };
    return { type: 'SET_TEMPERATURE', temperature: result.value };
}

store.dispatch( retrieveTemperature() );

In this example, when we dispatch retrieveTemperature, it will trigger the control handler to take effect, issuing the network request and assigning the result into the result variable. Only once the
request has completed does the action creator proceed to return the SET_TEMPERATURE action type.

API

default

Creates a Redux middleware, given an object of controls where each key is an action type for which to act upon, the value a function which returns either a promise which is to resolve when evaluation of the action should continue, or a value. The value or resolved promise value is assigned on the return value of the yield assignment. If the control handler returns undefined, the execution is not continued.

Parameters

  • controls Record< string, ( value: AnyAction ) => Promise< boolean > | boolean >: Object of control handlers.

Returns

  • Middleware: Co-routine runtime

Motivation

@wordpress/redux-routine shares many of the same motivations as other similar generator-based Redux side effects solutions, including redux-saga. Where it differs is in being less opinionated by virtue of its minimalism. It includes no default controls, offers no tooling around splitting logic flows, and does not include any error handling out of the box. This is intended in promoting approachability to developers who seek to bring asynchronous or conditional continuation flows to their applications without a steep learning curve.

The primary motivations include, among others:

  • Testability: Since an action creator yields plain action objects, the behavior of their resolution can be easily substituted in tests.
  • Controlled flexibility: Control flows can be implemented without sacrificing the expressiveness and intentionality of an action type. Other solutions like thunks or promises promote ultimate flexibility, but at the expense of maintainability manifested through deep coupling between action types and incidental implementation.
  • A common domain language for expressing data flows: Since controls are centrally defined, it requires the conscious decision on the part of a development team to decide when and how new control handlers are added.

Testing

Since your action creators will return an iterable generator of plain action objects, they are trivial to test.

Consider again our above example:

function* retrieveTemperature() {
    const result = yield { type: 'FETCH_JSON', url: 'https://' };
    return { type: 'SET_TEMPERATURE', temperature: result.value };
}

A test case (using Node’s assert built-in module) may be written as:

import { deepEqual } from 'assert';

const action = retrieveTemperature();

deepEqual( action.next().value, {
    type: 'FETCH_JSON',
    url: 'https://',
} );

const jsonResult = { value: 10 };
deepEqual( action.next( jsonResult ).value, {
    type: 'SET_TEMPERATURE',
    temperature: 10,
} );

If your action creator does not assign the yielded result into a variable, you can also use Array.from to create an array from the result of the action creator.

Contributing to this package

This is an individual package that’s part of the Gutenberg project. The project is organized as a monorepo. It’s made up of multiple self-contained software packages, each with a specific purpose. The packages in this monorepo are published to npm and used by WordPress as well as other software projects.

To find out more about contributing to this package or Gutenberg as a whole, please read the project’s main contributor guide.