tunnckoCore / ideas

:notebook: My centralized place for ideas, thoughts and todos. Raw, PoC implementations and so on... :star:
http://j.mp/1stW47C
6 stars 0 forks source link

dush-plugins #74

Open tunnckoCore opened 7 years ago

tunnckoCore commented 7 years ago

Run in series, settle mode (fail fast), plus life-cycle hooks

'use strict'

var redolent = require('redolent')
var mixinDeep = require('mixin-deep')
var betterUse = require('dush-better-use')
var createPlugin = require('minibase-create-plugin')

var dushPlugins = createPlugin('dush-plugins', function (app, opts) {
  app.options = mixinDeep({}, app.options, opts)

  app.use(betterUse())

  app.define('run', function run (a, b, c) {
    var args = [].slice.call(arguments)
    var resolve = redolent(function resolver () {
      app.emit('start', app)
    }, app.options)

    return app._plugins.reduce(reducer(app, args), resolve()).then(function () {
      app.emit('finish', app)
    }).catch(function (err) {
      app.emit('error', err)
      app.emit('finish', app)
    })
  })

  return app
})

function reducer (app, args) {
  return function reducer (promise, handler) {
    return promise.then(function () {
      app.emit('beforeEach', app, handler, args)
      return redolent(handler, {
        Promise: app.options.Promise,
        context: app.options.context || handler,
        args: args
      })()
        .then(function (res) {
          handler.value = res
          app.emit('afterEach', app, handler)
        })
        .catch(function (err) {
          handler.reason = err
          app.emit('afterEach', app, handler)
        })
    })
  }
}