跳到主要内容

Manager

Managers 负责处理全局副作用。它们就像 watchEffect(),只不过作用于中心数据 store。

默认的 manager 负责运行 Data Client 提供的异步行为,例如获取数据和订阅。你可以通过 getDefaultManagers() 配置它们,并添加你自己的 Managers。

每个 Manager 都实现 middleware,它把 Manager 接入 store 的控制流。 init() 和 cleanup() 把它接入 store 的生命周期,用于初始化和清理。

type Dispatch = (action: ActionTypes) => Promise<void>;

type Middleware = (controller: Controller) => (next: Dispatch) => Dispatch;

interface Manager {
middleware: Middleware;
cleanup(): void;
init?: (state: State<any>) => void;
}

生存期​

每个 store 都有自己的 Manager。Manager 的代码处于以下三种生存期之一:

生存期持续时间保存内容
Config整个页面传给构造函数的选项,比如 URL 或回调
Store一个 store,从 managers 函数运行到卸载关于该 store 的实例字段,比如进行中的获取
Active从 init() 到 cleanup()定时器、连接和监听器

因此构造函数只保存它的选项。

生命周期​

middleware​

middleware 的工作方式与 redux middleware 相同,只是 next() 会返回一个 Promise。

这个 promise 会在 DataClientPlugin store 提交更新后 resolve,因此 Manager 可以 await next() 来基于新状态执行工作。

中间件可以在 action 被派发时读取它们,也可以派发自己的 action。

init(state)​

在 Manager 启动时调用。在这里启动定时器和连接。

cleanup()​

在 Manager 停止时调用。在这里停止定时器和连接。

向 Reactive Data Client 添加 manager​

向 DataClientPlugin 的 managers 选项传入一个函数。它对每个应用运行一次。

main.ts
import { createApp } from 'vue';
import { DataClientPlugin, getDefaultManagers } from '@data-client/vue';
import App from './App.vue';
import MyManager from './MyManager';

const managers = () => [new MyManager(), ...getDefaultManagers()];

const app = createApp(App);
app.use(DataClientPlugin, { managers });
app.mount('#app');

请在模块顶层定义这个函数:它只包含配置。

action 会按数组顺序依次经过各个 manager。请把自定义 manager 放在默认 manager 之前:NetworkManager 会自行处理大多数 FETCH action,而不会把它们继续传递下去。

控制流​

Manager 通过其生命周期方法和中间件接入 DataClientPlugin store。它们读取和派发 action,并读取 store 的状态。

Manager 的 flux 流程Manager 的 flux 流程

middleware 的职责是派发 action、响应 action,或者两者兼而有之。

派发 Action​

Controller 提供了类型安全的 action 派发器。

import type { Controller, Manager, Middleware } from '@data-client/vue';
import CurrentTime from './CurrentTime';

export default class TimeManager implements Manager {
  declare protected controller: Controller;
  declare protected intervalID?: ReturnType<typeof setInterval>;

  middleware: Middleware = controller => {
    this.controller = controller;
    return next => async action => next(action);
  };

  init() {
    this.intervalID = setInterval(() => {
      this.controller.set(
        CurrentTime,
        { id: 1 },
        { id: 1, time: Date.now() },
      );
    }, 1000);
  }

  cleanup() {
    clearInterval(this.intervalID);
  }
}

读取和消费 Action​

actionTypes 包含用于区分不同 action 的所有常量。

import type { Manager, Middleware } from '@data-client/vue';
import { actionTypes } from '@data-client/vue';

export default class LoggingManager implements Manager {
  middleware: Middleware = controller => next => async action => {
    switch (action.type) {
      case actionTypes.SET_RESPONSE:
        if (action.endpoint.sideEffect) {
          console.info(
            `${action.endpoint.name} ${JSON.stringify(action.response)}`,
          );
          // wait for state update to be committed
          await next(action);
          // get the data from the store, which may be merged with existing state
          const { data } = controller.getResponse(
            action.endpoint,
            ...action.args,
            controller.getState(),
          );
          console.info(`${action.endpoint.name} ${JSON.stringify(data)}`);
          return;
        }
      // actions must be explicitly passed to next middleware
      default:
        return next(action);
    }
  };

  cleanup() {}
}

在每个 case 中,TypeScript 会收窄 action 的类型,因此你可以安全地访问其成员。

要消费某个 action,不要调用 next()。

import type {
  Manager,
  Middleware,
  EntityInterface,
} from '@data-client/vue';
import { actionTypes } from '@data-client/vue';
import isEntity from './isEntity';

export default class CustomSubsManager implements Manager {
  declare protected entities: Record<string, EntityInterface>;

  middleware: Middleware = controller => next => async action => {
    switch (action.type) {
      case actionTypes.SUBSCRIBE:
      case actionTypes.UNSUBSCRIBE:
        const { schema } = action.endpoint;
        // only process registered entities
        if (schema && isEntity(schema) && schema.key in this.entities) {
          if (action.type === actionTypes.SUBSCRIBE) {
            this.subscribe(schema.key, action.args[0]?.product_id);
          } else {
            this.unsubscribe(schema.key, action.args[0]?.product_id);
          }

          // consume subscription if we use it
          return Promise.resolve();
        }
      default:
        return next(action);
    }
  };

  cleanup() {}

  subscribe(channel: string, product_id: string) {}
  unsubscribe(channel: string, product_id: string) {}
}

用 return Promise.resolve(); 代替 next(action),可以阻止排在这个 manager 之后的 manager 看到该 action。

类型:FETCH、SET、SET_RESPONSE、 RESET、SUBSCRIBE、UNSUBSCRIBE、 INVALIDATE、INVALIDATEALL、EXPIREALL

使用场景​

常见 Manager 使用场景的最小示例: