index.js 7.4 KB

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