美文网首页
06-19集中处理请求的Orchestra

06-19集中处理请求的Orchestra

作者: NOTEBOOK2 | 来源:发表于2018-06-19 19:54 被阅读0次


当我们的组件里请求非常多(比如今天的需求是一个组件里处理12个请求…),给每一个请求都写一遍loading和错误处理等非常繁琐,因此统一管理请求就很有必要了。orchestra原义为交响乐,这里用作统一处理请求的组件名称。
orchestra本质为HOC高阶组件。


使用时需要定义的属性包括type,action,runner和可选的prop,initialParams.


其中,runner代表调用的函数。

type Runner = (...args: any[]) => IterableIterator<any>

以其中一组CRUD为例,564行的runner即调用522行的load函数,返回值赋给this.props.section.最后的585行为初始值。


loading为一个数组,通过toggleLoading函数来判断当前正在加载还是加载完成的状态。



在展示组件内部,则通过数组的some方法选择展示加载组件还是加载后的页面。


错误处理是一个对象,在构造函数里赋空值,在render渲染组件之前的componentWillMount里改变其值。


完整的源码长这样:

import { runSaga, Task as RootTask } from "redux-saga"
import { takeLatest, put } from "redux-saga/effects"
import EventEmitter, { Action } from "./EventEmitter"
import React from "react"

export enum Type {
  INIT,
  BLOCK,
  NON_BLOCK,
}

type Runner = (...args: any[]) => IterableIterator<any>

interface Task<Payloads, Actions extends number> {
  type: Type
  action: Actions
  runner: Runner
  prop?: keyof Payloads
  initParams?: any
}

type RecuPartial<T> = { [key in keyof T]?: RecuPartial<T[key]> }

interface State<T, Actions> {
  results: RecuPartial<T>
  loading: Actions[]
  errors: {
    [key: number]: string
  }
}

function* taskRunner(runner: Runner, props: any, { type, params, onSuccess }: Action<any>) {
  try {
    const payload = yield* runner(props, params)
    yield put({
      type,
      payload,
      onSuccess,
    })
  } catch (err) {
    yield put({ type, err })
  }
}

function connOrchestra<Props, Payloads, Actions extends number>(
  tasks: Array<Task<Payloads, Actions>>,
  initPayloadsState?: RecuPartial<Payloads>,
) {
  return <P extends WithOrchestra<Payloads, Actions>>(Comp: React.ComponentType<P>) => {
    type T = Omit<P, keyof WithOrchestra<Payloads, Actions>> & Props
    return class Orchestra extends React.Component<T, State<Payloads, Actions>> {
      rootTask: RootTask
      emitter: EventEmitter
      currentActions: Actions[]
      constructor(props: T) {
        super(props)

        this.toggleLoading = this.toggleLoading.bind(this)
        this.saga = this.saga.bind(this)
        this.call = this.call.bind(this)

        this.emitter = new EventEmitter()
        this.currentActions = []
        this.state = {
          results: initPayloadsState,
          loading: [],
          errors: {},
        }
      }
      componentWillMount() {
        this.rootTask = runSaga(
          {
            subscribe: cb => this.emitter.addEventListener(cb),
            dispatch: (r: any) => {
              const { type, payload, onSuccess, err } = r
              const task = tasks.find(task => task.action === type)

              if (err) {
                this.setState(({ errors }: any) => ({
                  errors: {
                    ...errors,
                    [task.action]: err.message,
                  },
                }))
              } else {
                if (task.prop) {
                  this.setState(({ results }: any) => ({
                    results: {
                      ...results,
                      [task.prop]: payload,
                    },
                  }))
                }
              }

              this.toggleLoading(task)
              if (onSuccess) {
                onSuccess()
              }
            },
            onError: e => {
              console.error(e) /* tslint:disable-line no-console */
            },
          },
          this.saga,
        )
        for (const task of tasks) {
          if (task.type === Type.INIT) {
            this.call(task.action, task.initParams)
          }
        }
      }
      *saga() {
        for (const { action, runner } of tasks) {
          yield takeLatest(({ type }: Action<any>) => type === action, taskRunner as any, runner, this.props)
        }
      }
      toggleLoading({ action }: Task<Payloads, Actions>) {
        this.setState(({ loading }) => {
          loading = loading.includes(action) ? loading.filter(a => a !== action) : [...loading, action]
          return { loading }
        })
      }
      call(action: Actions, params: any) {
        return new Promise((onSuccess, reject) => {
          if (this.currentActions.includes(action)) {
            reject()
          }
          const task = tasks.find(task => action === task.action)
          if (!task) {
            reject("task not found")
          }
          this.toggleLoading(task)
          this.emitter.dispatch({
            type: action,
            params,
            onSuccess,
          })
        })
      }
      end() {
        this.rootTask.cancel()
      }
      render() {
        const { loading, errors, results } = this.state
        return <Comp {...this.props} loading={loading} errors={errors} {...results} call={this.call} />
      }
    }
  }
}

export default connOrchestra

相关文章

网友评论

      本文标题:06-19集中处理请求的Orchestra

      本文链接:https://www.haomeiwen.com/subject/wxdzeftx.html