1.0.3 • Published 4 years ago

@irim/ds-core v1.0.3

Weekly downloads
6
License
BSD-3-Clause
Repository
-
Last release
4 years ago

DS-CORE

version license downloads

快速使用

安装

$ npm install --save @irim/ds-core
import { Core, Plugin, createApplyChain, uuid, random } from '@irim/ds-core';

Core

DS 核心引擎,用于注册插件、处理事件等 (继承自 Events )

const ds = new Core();

// 修改配置项
ds.setConfig({
  pluginA: { foo: 'bar' }, // 用于 pluginA 的初始化参数
});

// 注册插件,初始化后会执行插件的 init 方法
//     注册成功后,可用 ds.pluginA 的方式获取到插件实例
ds.register('pluginA', PluginA, {
  goo: 1001, // 实际初始化的参数是此参数与 config.pluginA 的合并数据
});

// 卸载插件,会执行插件的 destroy 方法
ds.unregister('pluginA');

事件相关的接口请参考 Events 文档

Plugin

基础插件类,所有 ds 插件必须继承此类,不能直接用 new 的方式初始化;Plugin 继承自 Events,同样包含事件能力。

需要重写的抽象方法:

  • init() 在插件注册时会被调用
  • destroy() 在插件卸载前会被调用
// 向调用链添加一个中间件
ds.pluginA.use(async ctx => {
  console.log('before...');
  ctx.next();
  console.log('after...');
});

// 创建并执行调用链
ds.pluginA.run(options);

工具类方法

  1. createApplyChain(middlewares: Function[], scope?: Object): Function 创建一个调用链

scope 表示执行每个 middleware 的上下文

async function middlewareA(ctx) {
  console.log('---- 1');
  ctx.next();
  console.log('---- 4');
}

async function middlewareB(ctx) {
  console.log('---- 2');
  ctx.next();
  console.log('---- 3');
}

const invoke = createApplyChain([middlewareA, middlewareB]);
invoke(); // 打印顺序: 1, 2, 3, 4
  1. random(min: number, max?: number): number 返回 [min, max] 的随机整数

  2. uuid(): string 创建一个唯一的ID

  3. logger.{debug|error|warn|info|success|line}(...args): void 控制台打印日志

logger.debug('Hello', 'Lilith');
logger.info('GET /api/todo', { message: 'say hello' });
  1. batchExecSync(callbacks: Function[], args?: Array, scope?: object) 批量同步执行方法
const callback1 = (data) => { return data.content };
const callback2 = (data) => { throw new Error('custom error') };

// [{ success: true, result: 'hello' }, { success: false, error: Error }]
const result = batchExecSync([callback1, callback2], [{ content: 'hello' }]);
  1. batchExecAsync(callbacks: Function[], args?: Array, scope?: object) 批量异步执行方法
const callback1 = (data) => { return Promise.resolve(data.content) };
const callback2 = (data) => { return Promise.reject(new Error('custom error')) };

// [{ success: true, result: 'hello' }, { success: false, error: Error }]
const result = await batchExecAsync([callback1, callback2], [{ content: 'hello' }]);

定义一个插件

class PluginA extends Plugin {
  init() {
    this.registerMiddleware();
  }

  // 注册插件执行中间件
  registerMiddleware() {
    this.use(async ctx => {
      console.log('before');
      await ctx.next();
      console.log('after');
    });

    this.use(async ctx => {
      ctx.response = await request('/api/todo');
      await ctx.next();
    });
  }

  async getTodoList() {
    const { response } = await this.run();
    // ....
  }
}

LICENSE

BSD-3-Clause License