segi-tool-envpipe
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

环境管道工具

背景

有很多同一个业务接入APP,公众号,小程序,以及第三方APP等。各自环境需要处理的接入逻辑都有不同,导致接入逻辑复杂,为解决此问题特设计了此工具。

特性

  • 简单易用,整个工具库只有三个API
  • 支持 TypeScript
  • 支持 npm 安装

安装

$ npm install segi-tool-envpipe -S

使用

import EnvPipe from 'segi-tool-envpipe'
// 实例化环境处理管道
// 在 TS 中需传入泛型,在 complete 中需 resolve 出对应格式的数据。
const envPipe = new EnvPipe<{ name: string }>()
// 默认环境处理
envPipe.defaultPipe = function () {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ name: '我是默认环境' })
    }, 2000)
  })
}
// 微信环境处理
envPipe.push({
  // 环境标识符
  name: 'wx',
  // 环境判断逻辑,返回布尔值
  in () {
    return /wx/.test(navigator.userAgent.toLowerCase())
  },
  // 环境处理函数,返回 Promise 函数
  complete () {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({ name: '我是微信环境' })
      }, 2000)
    })
  }
})

API

defaultPipe: 默认环境处理

当所有环境都不匹配的时候,执行此默认处理。用法为直接重写覆盖实例方法。

// 默认环境处理
envPipe.defaultPipe = function () {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ name: '我是默认环境' })
    }, 2000)
  })
}

push: 推入环境处理管道

将管道定义推入实例,注意推入并不代表执行。

envPipe.push({
  // 环境标识符,不能重复
  name: 'wx',
  // 环境判断逻辑,返回布尔值
  in () {
    return /wx/.test(navigator.userAgent.toLowerCase())
  },
  // 环境处理函数,返回 Promise<T> 函数,其中泛型 T 与实例化环境管道所传入的一致。
  complete () {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({ name: '我是微信环境' })
      }, 2000)
    })
  }
})

start: 启动管道处理

执行了 start 之后,才会启动管道进行处理,有环境返回 true之后结束处理。通过传入的参数控制要执行的管道以及执行顺序。管道中的in判断逻辑返回为 true之后即不再执行后续管道。

// 参数为管道的 name 值数组,数组顺序为管道执行顺序,顺序执行管道的 in 方法,直到返回 true 为止
envPipe.start([
  'wx',
  'qq',
]).then(el => {
  console.log(el)
  new Vue({
    router,
    store,
    render: h => h(App)
  }).$mount('#app')
})

Readme

Keywords

none

Package Sidebar

Install

npm i segi-tool-envpipe

Weekly Downloads

9

Version

1.1.0

License

ISC

Unpacked Size

17.9 kB

Total Files

5

Last publish

Collaborators

  • zuley