adapter.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. 'use strict';
  2. const fs = require('graceful-fs');
  3. function createSyncFs(fs) {
  4. const methods = ['mkdir', 'realpath', 'stat', 'rmdir', 'utimes'];
  5. const newFs = { ...fs };
  6. methods.forEach((method) => {
  7. newFs[method] = (...args) => {
  8. const callback = args.pop();
  9. let ret;
  10. try {
  11. ret = fs[`${method}Sync`](...args);
  12. } catch (err) {
  13. return callback(err);
  14. }
  15. callback(null, ret);
  16. };
  17. });
  18. return newFs;
  19. }
  20. // ----------------------------------------------------------
  21. function toPromise(method) {
  22. return (...args) => new Promise((resolve, reject) => {
  23. args.push((err, result) => {
  24. if (err) {
  25. reject(err);
  26. } else {
  27. resolve(result);
  28. }
  29. });
  30. method(...args);
  31. });
  32. }
  33. function toSync(method) {
  34. return (...args) => {
  35. let err;
  36. let result;
  37. args.push((_err, _result) => {
  38. err = _err;
  39. result = _result;
  40. });
  41. method(...args);
  42. if (err) {
  43. throw err;
  44. }
  45. return result;
  46. };
  47. }
  48. function toSyncOptions(options) {
  49. // Shallow clone options because we are oging to mutate them
  50. options = { ...options };
  51. // Transform fs to use the sync methods instead
  52. options.fs = createSyncFs(options.fs || fs);
  53. // Retries are not allowed because it requires the flow to be sync
  54. if (
  55. (typeof options.retries === 'number' && options.retries > 0) ||
  56. (options.retries && typeof options.retries.retries === 'number' && options.retries.retries > 0)
  57. ) {
  58. throw Object.assign(new Error('Cannot use retries with the sync api'), { code: 'ESYNC' });
  59. }
  60. return options;
  61. }
  62. module.exports = {
  63. toPromise,
  64. toSync,
  65. toSyncOptions,
  66. };