Lawsun d230cfbce0 first commit il y a 1 an
..
History.md d230cfbce0 first commit il y a 1 an
LICENSE d230cfbce0 first commit il y a 1 an
README.md d230cfbce0 first commit il y a 1 an
index.d.ts d230cfbce0 first commit il y a 1 an
index.js d230cfbce0 first commit il y a 1 an
package.json d230cfbce0 first commit il y a 1 an

README.md

sdk-base

NPM version build status Test coverage David deps npm download

A base class for sdk with some common & useful functions.

Installation

$ npm install sdk-base

Usage

Constructor argument:

  • {Object} options
    • {String} [initMethod] - the async init method name, the method should be a generator function or a function return promise. If set, will execute the function in the constructor.
  'use strict';

  const co = require('co');
  const Base = require('sdk-base');

  class Client extends Base {
    constructor() {
      super({
        initMethod: 'init',
      });
    }

    * init() {
      // put your async init logic here
    }
    // support async function too
    // async init() {
    //   // put your async init logic here
    // }
  }

  co(function* () {
    const client = new Client();
    // wait client ready, if init failed, client will throw an error.
    yield client.ready();

    // support generator event listener
    client.on('data', function* (data) {
      // put your async process logic here
      //
      // @example
      // ----------
      // yield submit(data);
    });

    client.emit('data', { foo: 'bar' });

  }).catch(err => { console.error(err); });

API

  • .ready(flagOrFunction) flagOrFunction is optional, and the argument type can be Boolean, Error or Function.
  // init ready
  client.ready(true);
  // init failed
  client.ready(new Error('init failed'));

  // listen client ready
  client.ready(err => {
    if (err) {
      console.log('client init failed');
      console.error(err);
      return;
    }
    console.log('client is ready');
  });

  // support promise style call
  client.ready()
    .then(() => { ... })
    .catch(err => { ... });

  // support generator style call
  yield client.ready();
  client.on('data', function* (data) {
    // your async process logic here
  });
  client.once('foo', function* (bar) {
    // ...
  });

  // listen error event
  client.on('error', err => {
    console.error(err.stack);
  });
  • .await(event): await an event, return a promise, and it will resolve(reject if event is error) once this event emmited.
  co(function* () {
    const data = yield client.await('data');
  });
  co(function* () {
    const o = yield client.awaitFirst([ 'foo', 'bar' ]);
    if (o.event === 'foo') {
      // ...
    }
    if (o.event === 'bar') {
      // ...
    }
  });
  • ._close(): The _close() method is called by close, It can be overridden by child class, but should not be called directly. It must return promise or generator.

  • .close(): The close() method is used to close the instance.

License

MIT