index.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. const { promisify, callbackify } = require('util')
  2. const pLimit = require('p-limit')
  3. module.exports = {
  4. promisify,
  5. promisifyAll,
  6. promisifyClass,
  7. promisifyMultiResult,
  8. callbackify,
  9. callbackifyAll,
  10. callbackifyMultiResult,
  11. expressify,
  12. expressifyErrorHandler,
  13. promiseMapWithLimit,
  14. }
  15. /**
  16. * Promisify all functions in a module.
  17. *
  18. * This is meant to be used only when all functions in the module are async
  19. * callback-style functions.
  20. *
  21. * It's very much tailored to our current module structure. In particular, it
  22. * binds `this` to the module when calling the function in order not to break
  23. * modules that call sibling functions using `this`.
  24. *
  25. * This will not magically fix all modules. Special cases should be promisified
  26. * manually.
  27. *
  28. * The second argument is a bag of options:
  29. *
  30. * - without: an array of function names that shouldn't be promisified
  31. *
  32. * - multiResult: an object whose keys are function names and values are lists
  33. * of parameter names. This is meant for functions that invoke their callbacks
  34. * with more than one result in separate parameters. The promisifed function
  35. * will return these results as a single object, with each result keyed under
  36. * the corresponding parameter name.
  37. */
  38. function promisifyAll(module, opts = {}) {
  39. const { without = [], multiResult = {} } = opts
  40. const promises = {}
  41. for (const propName of Object.getOwnPropertyNames(module)) {
  42. if (without.includes(propName)) {
  43. continue
  44. }
  45. const propValue = module[propName]
  46. if (typeof propValue !== 'function') {
  47. continue
  48. }
  49. if (multiResult[propName] != null) {
  50. promises[propName] = promisifyMultiResult(
  51. propValue,
  52. multiResult[propName]
  53. ).bind(module)
  54. } else {
  55. promises[propName] = promisify(propValue).bind(module)
  56. }
  57. }
  58. return promises
  59. }
  60. /**
  61. * Promisify all methods in a class.
  62. *
  63. * Options are the same as for promisifyAll
  64. */
  65. function promisifyClass(cls, opts = {}) {
  66. const promisified = class extends cls {}
  67. const { without = [], multiResult = {} } = opts
  68. for (const propName of Object.getOwnPropertyNames(cls.prototype)) {
  69. if (propName === 'constructor' || without.includes(propName)) {
  70. continue
  71. }
  72. const propValue = cls.prototype[propName]
  73. if (typeof propValue !== 'function') {
  74. continue
  75. }
  76. if (multiResult[propName] != null) {
  77. promisified.prototype[propName] = promisifyMultiResult(
  78. propValue,
  79. multiResult[propName]
  80. )
  81. } else {
  82. promisified.prototype[propName] = promisify(propValue)
  83. }
  84. }
  85. return promisified
  86. }
  87. /**
  88. * Promisify a function that returns multiple results via additional callback
  89. * parameters.
  90. *
  91. * The promisified function returns the results in a single object whose keys
  92. * are the names given in the array `resultNames`.
  93. *
  94. * Example:
  95. *
  96. * function f(callback) {
  97. * return callback(null, 1, 2, 3)
  98. * }
  99. *
  100. * const g = promisifyMultiResult(f, ['a', 'b', 'c'])
  101. *
  102. * const result = await g() // returns {a: 1, b: 2, c: 3}
  103. */
  104. function promisifyMultiResult(fn, resultNames) {
  105. function promisified(...args) {
  106. return new Promise((resolve, reject) => {
  107. try {
  108. fn.bind(this)(...args, (err, ...results) => {
  109. if (err != null) {
  110. return reject(err)
  111. }
  112. const promiseResult = {}
  113. for (let i = 0; i < resultNames.length; i++) {
  114. promiseResult[resultNames[i]] = results[i]
  115. }
  116. resolve(promiseResult)
  117. })
  118. } catch (err) {
  119. reject(err)
  120. }
  121. })
  122. }
  123. return promisified
  124. }
  125. /**
  126. * Reverse of `promisifyAll`.
  127. *
  128. * Callbackify all async functions in a module and return them in an object. In
  129. * contrast with `promisifyAll`, all other exports from the module are added to
  130. * the result.
  131. *
  132. * This is meant to be used like this:
  133. *
  134. * const MyPromisifiedModule = {...}
  135. * module.exports = {
  136. * ...callbackifyAll(MyPromisifiedModule),
  137. * promises: MyPromisifiedModule
  138. * }
  139. *
  140. * @param {Object} module - The module to callbackify
  141. * @param {Object} opts - Options
  142. * @param {Array<string>} opts.without - Array of method names to exclude from
  143. * being callbackified
  144. * @param {Object} opts.multiResult - Spec of methods to be callbackified with
  145. * callbackifyMultiResult()
  146. */
  147. function callbackifyAll(module, opts = {}) {
  148. const { without = [], multiResult = {} } = opts
  149. const callbacks = {}
  150. for (const propName of Object.getOwnPropertyNames(module)) {
  151. if (without.includes(propName)) {
  152. continue
  153. }
  154. const propValue = module[propName]
  155. if (typeof propValue === 'function') {
  156. if (propValue.constructor.name === 'AsyncFunction') {
  157. if (multiResult[propName] != null) {
  158. callbacks[propName] = callbackifyMultiResult(
  159. propValue,
  160. multiResult[propName]
  161. ).bind(module)
  162. } else {
  163. callbacks[propName] = callbackify(propValue).bind(module)
  164. }
  165. } else {
  166. callbacks[propName] = propValue.bind(module)
  167. }
  168. } else {
  169. callbacks[propName] = propValue
  170. }
  171. }
  172. return callbacks
  173. }
  174. /**
  175. * Reverse the effect of `promisifyMultiResult`.
  176. *
  177. * This is meant for providing a temporary backward compatible callback
  178. * interface while we migrate to promises.
  179. */
  180. function callbackifyMultiResult(fn, resultNames) {
  181. function callbackified(...args) {
  182. const [callback] = args.splice(-1)
  183. fn(...args)
  184. .then(result => {
  185. const cbResults = resultNames.map(resultName => result[resultName])
  186. callback(null, ...cbResults)
  187. })
  188. .catch(err => {
  189. callback(err)
  190. })
  191. }
  192. return callbackified
  193. }
  194. /**
  195. * Transform an async function into an Express middleware
  196. *
  197. * Any error will be passed to the error middlewares via `next()`
  198. */
  199. function expressify(fn) {
  200. return (req, res, next) => {
  201. fn(req, res, next).catch(next)
  202. }
  203. }
  204. /**
  205. * Transform an async function into an Error Handling Express middleware
  206. *
  207. * Any error will be passed to the error middlewares via `next()`
  208. */
  209. function expressifyErrorHandler(fn) {
  210. return (err, req, res, next) => {
  211. fn(err, req, res, next).catch(next)
  212. }
  213. }
  214. /**
  215. * Map values in `array` with the async function `fn`
  216. *
  217. * Limit the number of unresolved promises to `concurrency`.
  218. */
  219. function promiseMapWithLimit(concurrency, array, fn) {
  220. const limit = pLimit(concurrency)
  221. return Promise.all(array.map(x => limit(() => fn(x))))
  222. }