progress.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Subs
  2. const channels = require('../channels')
  3. const map = new Map()
  4. function get (id, context) {
  5. return map.get(id)
  6. }
  7. function set (data, context) {
  8. const { id } = data
  9. let progress = get(id, context)
  10. if (!progress) {
  11. progress = data
  12. map.set(id, Object.assign({}, {
  13. status: null,
  14. error: null,
  15. info: null,
  16. args: null,
  17. progress: -1
  18. }, progress))
  19. } else {
  20. Object.assign(progress, data)
  21. }
  22. context.pubsub.publish(channels.PROGRESS_CHANGED, { progressChanged: progress })
  23. return progress
  24. }
  25. function remove (id, context) {
  26. context.pubsub.publish(channels.PROGRESS_REMOVED, { progressRemoved: id })
  27. return map.delete(id)
  28. }
  29. async function wrap (id, context, operation) {
  30. set({ id }, context)
  31. let result
  32. try {
  33. result = await operation(data => {
  34. set(Object.assign({ id }, data), context)
  35. })
  36. } catch (error) {
  37. console.error(error)
  38. set({ id, error: error.message }, context)
  39. }
  40. remove(id, context)
  41. return result
  42. }
  43. module.exports = {
  44. get,
  45. set,
  46. remove,
  47. wrap
  48. }