Home Reference Source Repository

es6/Wyst.js

import Promise        from 'bluebird'

import Expressive     from './utils/Expressive'
import * as Time      from './utils/Time'
import Ensure         from './utils/Ensure'
import {Plugin_Error} from './Errors'
import Queue          from './Queue/Queue'

/**
 * @class Wyst
 */
export default class Wyst extends Expressive {
  /**
   * generates our main Wyst instance
   *
   * @method     constructor
   * @param      {Object}  config  The necessary config for our instance
   */
  constructor (config) {
    super()
    this.config      = config
    this.startTime   = Date.now()
    this.extensions  = {}

    Promise.props({
      queue : Queue.create()
    }).bind(this)
    .then(this.assign)
    .then(this.bringOnline)

    return this
  }

  /**
   * returns how long this Wyst instance has been alive for
   *
   * @property     uptime
   */
  get uptime () {
    return Time.humanize(this.startTime)
  }

  /**
   * sets an internal extension to
   * 
   * @method set
   * @param {Object} extensions   the properties and values to assign to the Wyst instance
   * @param {Any}    val          the val for namespace
   * @return {this}
   */
  assign (extensions) {
    Object.assign(this.extensions, extensions)
    return this
  }

  /**
   * returns the value for a namespace
   */

  get (namespace) {
    return this.extensions[namespace]
  }

  /**
   * initializes a plugin with the Wyst instance
   *
   * @method     plugin
   * @param      {String}    namespace  The namespace for the plugin to live under
   * @param      {Function}  init       
   * @return     {this}    
   */
  plugin (namespace, init) {
    this.extensions[namespace] = init(this)

    this[namespace] = this[namespace] 
      ? Ensure.throw( new Plugin_Error(namespace) )
      : function _pluginRef () { return this.extensions[namespace] }
    return this
  }

  /**
   * alerts any interested Listeners that Wyst is now ready.
   */
  bringOnline () {
    this.is("online")
  }

}