| 1 |
|
|---|
| 2 | var thenify = require('thenify')
|
|---|
| 3 |
|
|---|
| 4 | module.exports = thenifyAll
|
|---|
| 5 | thenifyAll.withCallback = withCallback
|
|---|
| 6 | thenifyAll.thenify = thenify
|
|---|
| 7 |
|
|---|
| 8 | /**
|
|---|
| 9 | * Promisifies all the selected functions in an object.
|
|---|
| 10 | *
|
|---|
| 11 | * @param {Object} source the source object for the async functions
|
|---|
| 12 | * @param {Object} [destination] the destination to set all the promisified methods
|
|---|
| 13 | * @param {Array} [methods] an array of method names of `source`
|
|---|
| 14 | * @return {Object}
|
|---|
| 15 | * @api public
|
|---|
| 16 | */
|
|---|
| 17 |
|
|---|
| 18 | function thenifyAll(source, destination, methods) {
|
|---|
| 19 | return promisifyAll(source, destination, methods, thenify)
|
|---|
| 20 | }
|
|---|
| 21 |
|
|---|
| 22 | /**
|
|---|
| 23 | * Promisifies all the selected functions in an object and backward compatible with callback.
|
|---|
| 24 | *
|
|---|
| 25 | * @param {Object} source the source object for the async functions
|
|---|
| 26 | * @param {Object} [destination] the destination to set all the promisified methods
|
|---|
| 27 | * @param {Array} [methods] an array of method names of `source`
|
|---|
| 28 | * @return {Object}
|
|---|
| 29 | * @api public
|
|---|
| 30 | */
|
|---|
| 31 |
|
|---|
| 32 | function withCallback(source, destination, methods) {
|
|---|
| 33 | return promisifyAll(source, destination, methods, thenify.withCallback)
|
|---|
| 34 | }
|
|---|
| 35 |
|
|---|
| 36 | function promisifyAll(source, destination, methods, promisify) {
|
|---|
| 37 | if (!destination) {
|
|---|
| 38 | destination = {};
|
|---|
| 39 | methods = Object.keys(source)
|
|---|
| 40 | }
|
|---|
| 41 |
|
|---|
| 42 | if (Array.isArray(destination)) {
|
|---|
| 43 | methods = destination
|
|---|
| 44 | destination = {}
|
|---|
| 45 | }
|
|---|
| 46 |
|
|---|
| 47 | if (!methods) {
|
|---|
| 48 | methods = Object.keys(source)
|
|---|
| 49 | }
|
|---|
| 50 |
|
|---|
| 51 | if (typeof source === 'function') destination = promisify(source)
|
|---|
| 52 |
|
|---|
| 53 | methods.forEach(function (name) {
|
|---|
| 54 | // promisify only if it's a function
|
|---|
| 55 | if (typeof source[name] === 'function') destination[name] = promisify(source[name])
|
|---|
| 56 | })
|
|---|
| 57 |
|
|---|
| 58 | // proxy the rest
|
|---|
| 59 | Object.keys(source).forEach(function (name) {
|
|---|
| 60 | if (deprecated(source, name)) return
|
|---|
| 61 | if (destination[name]) return
|
|---|
| 62 | destination[name] = source[name]
|
|---|
| 63 | })
|
|---|
| 64 |
|
|---|
| 65 | return destination
|
|---|
| 66 | }
|
|---|
| 67 |
|
|---|
| 68 | function deprecated(source, name) {
|
|---|
| 69 | var desc = Object.getOwnPropertyDescriptor(source, name)
|
|---|
| 70 | if (!desc || !desc.get) return false
|
|---|
| 71 | if (desc.get.name === 'deprecated') return true
|
|---|
| 72 | return false
|
|---|
| 73 | }
|
|---|