1.0.7 • Published 1 year ago

waterfall-unitwork v1.0.7

Weekly downloads
-
License
ISC
Repository
-
Last release
1 year ago

介绍

工作性质类似middleware,具有上下文的特性

使用场景

  1. 串联请求
  2. 按流程处理业务

代码使用

// 串联请求
import WaterfallUnitWork from 'waterfall-unitwork';

// 明确上下文数据
type Data = {
  deptId?: string;
  users?: []
}

const tandemRequest = new WaterfallUnitWork<Data>({})
tandemRequest
      .add((ctx) => {
        // 请求部门 复制
        fetch('getDepeId').then((res) => {
          if (res.code === 200) {
            ctx.data.deptId = res.deptId
            // flag为true,代表进入下一个函数
            ctx.next(true)
          } else {
            // ctx为false,代表进入end函数
            // 错误信息也可以定义在ctx.data上
            ctx.next(false)
          }
        })
      })
      .add((ctx) => {
        console.log('ctx.data.deptId', ctx.data.deptId)
        // 根据ctx.data.deptId请求人员
      })
      .end((flag, ctx) => {
        // 根据flag判断是否业务处理成功
      })
// 根据进入微信小程序后解析的路径判断不同的业务
import WaterfallUnitWork from 'waterfall-unitwork';
import type {UnitWorkFn} from 'waterfall-unitwork'
/**
     * 登录节点
     * 判断是否登录
     * 类似的方法可重复声明,而后重复使用
     */
    const loginNode: UnitWorkFn<Record<string, any>> = (ctx) => {
      // 判断是否登录
      if (hasLogin()) {
        ctx.next(true)
      } else {
        // 1. 登录
        // 进行下一个节点
        ctx.next(true)
      }
    }
    // task1需要登录
    const task1 = new WaterfallUnitWork<Record<string, any>>({})
    // task2 需要登录
    const task2 = new WaterfallUnitWork<Record<string, any>>({})
    task1
      .add(loginNode)
      .add((ctx) => {
        // 其他业务
      })
      .end((flag, ctx) => {
        // 处理最终
      })
    task2
      .add((ctx) => {
        // 业务1
      })
      .add((ctx) => {
        // 业务2
      })
      .end((falg, ctx) => {
        // 最终业务
      })
1.0.7

1 year ago

1.0.6

1 year ago

1.0.5

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago