Blame view

code/finance_web/node_modules/bfj-node4/src/eventify.js 6.84 KB
a  
谢明辉 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
'use strict'

const check = require('check-types')
const EventEmitter = require('events').EventEmitter
const events = require('./events')
const promise = require('./promise')

const invalidTypes = {
  undefined: true, // eslint-disable-line no-undefined
  function: true,
  symbol: true
}

module.exports = eventify

/**
 * Public function `eventify`.
 *
 * Returns an event emitter and asynchronously traverses a data structure
 * (depth-first), emitting events as it encounters items. Sanely handles
 * promises, buffers, maps and other iterables. The event emitter is
 * decorated with a `pause` method that can be called to pause processing.
 *
 * @param data:       The data structure to traverse.
 *
 * @option promises:  'resolve' or 'ignore', default is 'resolve'.
 *
 * @option buffers:   'toString' or 'ignore', default is 'toString'.
 *
 * @option maps:      'object' or 'ignore', default is 'object'.
 *
 * @option iterables:  'array' or 'ignore', default is 'array'.
 *
 * @option circular:   'error' or 'ignore', default is 'error'.
 *
 * @option yieldRate:  The number of data items to process per timeslice,
 *                     default is 16384.
 *
 * @option Promise:      The promise constructor to use, defaults to bluebird.
 **/
function eventify (data, options) {
  options = options || {}

  const coercions = {}
  const emitter = new EventEmitter()
  const Promise = promise(options)
  const references = new Map()

  let count = 0
  let disableCoercions = false
  let ignoreCircularReferences
  let ignoreItems
  let pause
  let yieldRate

  emitter.pause = () => {
    let resolve
    pause = new Promise(res => resolve = res)
    return () => {
      pause = null
      count = 0
      resolve()
    }
  }
  parseOptions()
  setImmediate(begin)

  return emitter

  function parseOptions () {
    parseCoercionOption('promises')
    parseCoercionOption('buffers')
    parseCoercionOption('maps')
    parseCoercionOption('iterables')

    if (Object.keys(coercions).length === 0) {
      disableCoercions = true
    }

    if (options.circular === 'ignore') {
      ignoreCircularReferences = true
    }

    check.assert.maybe.positive(options.yieldRate)
    yieldRate = options.yieldRate || 16384
  }

  function parseCoercionOption (key) {
    if (options[key] !== 'ignore') {
      coercions[key] = true
    }
  }

  function begin () {
    return proceed(data)
      .catch(error => emit(events.error, error))
      .then(() => emit(events.end))
  }

  function proceed (datum) {
    if (++count % yieldRate !== 0) {
      return coerce(datum).then(after)
    }

    return new Promise((resolve, reject) => {
      setImmediate(() => {
        coerce(datum)
          .then(after)
          .then(resolve)
          .catch(reject)
      })
    })

    function after (coerced) {
      if (isInvalidType(coerced)) {
        return
      }

      if (coerced === false || coerced === true || coerced === null) {
        return literal(coerced)
      }

      if (Array.isArray(coerced)) {
        return array(coerced)
      }

      const type = typeof coerced

      switch (type) {
        case 'number':
          return value(coerced, type)
        case 'string':
          return value(escapeString(coerced), type)
        default:
          return object(coerced)
      }
    }
  }

  function coerce (datum) {
    if (disableCoercions || check.primitive(datum)) {
      return Promise.resolve(datum)
    }

    if (check.instanceStrict(datum, Promise)) {
      return coerceThing(datum, 'promises', coercePromise).then(coerce)
    }

    if (check.instanceStrict(datum, Buffer)) {
      return coerceThing(datum, 'buffers', coerceBuffer)
    }

    if (check.instanceStrict(datum, Map)) {
      return coerceThing(datum, 'maps', coerceMap)
    }

    if (
      check.iterable(datum) &&
      check.not.string(datum) &&
      check.not.array(datum)
    ) {
      return coerceThing(datum, 'iterables', coerceIterable)
    }

    if (check.function(datum.toJSON)) {
      return Promise.resolve(datum.toJSON())
    }

    return Promise.resolve(datum)
  }

  function coerceThing (datum, thing, fn) {
    if (coercions[thing]) {
      return fn(datum)
    }

    return Promise.resolve()
  }

  function coercePromise (p) {
    return p
  }

  function coerceBuffer (buffer) {
    return Promise.resolve(buffer.toString())
  }

  function coerceMap (map) {
    const result = {}

    return coerceCollection(map, result, (item, key) => {
      result[key] = item
    })
  }

  function coerceCollection (coll, target, push) {
    coll.forEach(push)

    return Promise.resolve(target)
  }

  function coerceIterable (iterable) {
    const result = []

    return coerceCollection(iterable, result, item => {
      result.push(item)
    })
  }

  function isInvalidType (datum) {
    return !! invalidTypes[typeof datum]
  }

  function literal (datum) {
    return value(datum, 'literal')
  }

  function value (datum, type) {
    return emit(events[type], datum)
  }

  function emit (event, eventData) {
    return (pause || Promise.resolve())
      .then(() => emitter.emit(event, eventData))
      .catch(err => {
        try {
          emitter.emit(events.error, err)
        } catch (_) {
          // When calling user code, anything is possible
        }
      })
  }

  function array (datum) {
    // For an array, collection:object and collection:array are the same.
    return collection(datum, datum, 'array', item => {
      if (isInvalidType(item)) {
        return proceed(null)
      }

      return proceed(item)
    })
  }

  function collection (obj, arr, type, action) {
    let ignoreThisItem

    return Promise.resolve()
      .then(() => {
        if (references.has(obj)) {
          ignoreThisItem = ignoreItems = true

          if (! ignoreCircularReferences) {
            return emit(events.error, new Error('Circular reference.'))
          }
        } else {
          references.set(obj, true)
        }
      })
      .then(() => emit(events[type]))
      .then(() => item(0))

    function item (index) {
      if (index >= arr.length) {
        if (ignoreThisItem) {
          ignoreItems = false
        }

        if (ignoreItems) {
          return Promise.resolve()
        }

        return emit(events.endPrefix + events[type])
          .then(() => references.delete(obj))
      }

      if (ignoreItems) {
        return item(index + 1)
      }

      return action(arr[index])
        .then(() => item(index + 1))
    }
  }

  function object (datum) {
    // For an object, collection:object and collection:array are different.
    return collection(datum, Object.keys(datum), 'object', key => {
      const item = datum[key]

      if (isInvalidType(item)) {
        return Promise.resolve()
      }

      return emit(events.property, key)
        .then(() => proceed(item))
    })
  }

  function escapeString (string) {
    string = JSON.stringify(string)
    return string.substring(1, string.length - 1)
  }
}