suggestions.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. // Subs
  2. const channels = require('../channels')
  3. // Connectors
  4. const { log } = require('../util/logger')
  5. const suggestions = []
  6. function list (context) {
  7. return suggestions
  8. }
  9. function findOne (id) {
  10. return suggestions.find(s => s.id === id)
  11. }
  12. function add (suggestion, context) {
  13. if (findOne(suggestion.id)) return
  14. if (!suggestion.importance) {
  15. suggestion.importance = 'normal'
  16. }
  17. suggestion.busy = false
  18. suggestions.push(suggestion)
  19. context.pubsub.publish(channels.SUGGESTION_ADDED, {
  20. suggestionAdded: suggestion
  21. })
  22. log('Suggestion added', suggestion.id)
  23. return suggestion
  24. }
  25. function remove (id, context) {
  26. const suggestion = findOne(id)
  27. if (!suggestion) return
  28. const index = suggestions.indexOf(suggestion)
  29. suggestions.splice(index, 1)
  30. context.pubsub.publish(channels.SUGGESTION_REMOVED, {
  31. suggestionRemoved: suggestion
  32. })
  33. log('Suggestion removed', suggestion.id)
  34. return suggestion
  35. }
  36. function clear (context) {
  37. for (const suggestion of suggestions) {
  38. remove(suggestion.id, context)
  39. }
  40. }
  41. function update (data, context) {
  42. const suggestion = findOne(data.id)
  43. if (!suggestion) return
  44. Object.assign(suggestion, data)
  45. context.pubsub.publish(channels.SUGGESTION_UPDATED, {
  46. suggestionUpdated: suggestion
  47. })
  48. log('Suggestion updated', suggestion.id)
  49. return suggestion
  50. }
  51. async function activate ({ id }, context) {
  52. const suggestion = findOne(id)
  53. if (!suggestion) return
  54. update({
  55. id: suggestion.id,
  56. busy: true
  57. }, context)
  58. let result, error
  59. try {
  60. result = await suggestion.handler()
  61. } catch (e) {
  62. error = e
  63. console.log(e)
  64. }
  65. update({
  66. id: suggestion.id,
  67. busy: false
  68. }, context)
  69. if (!error && (!result || !result.keep)) {
  70. remove(suggestion.id, context)
  71. }
  72. return suggestion
  73. }
  74. module.exports = {
  75. list,
  76. add,
  77. remove,
  78. clear,
  79. activate
  80. }