toggle.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /**
  2. * @author oldj
  3. * @blog http://oldj.net
  4. */
  5. 'use strict'
  6. const getUserHosts = require('../../actions/getUserHosts')
  7. const saveHosts = require('../../actions/saveHosts')
  8. const getPref = require('../../actions/getPref')
  9. const notify = require('../../actions/notify')
  10. const svr = require('../../svr')
  11. module.exports = (req, res) => {
  12. let id = req.param('id')
  13. let is_single
  14. getPref()
  15. .then(pref => {
  16. is_single = pref.choice_mode === 'single'
  17. })
  18. .then(() => getUserHosts())
  19. .then(list => {
  20. let item = list.find(i => i.id === id)
  21. if (!item) {
  22. res.end('not-found:' + id)
  23. return
  24. }
  25. item.on = !item.on
  26. if (item.on && is_single) {
  27. // 单选模式
  28. list.map(i => {
  29. if (i.id !== id) {
  30. i.on = false
  31. }
  32. })
  33. }
  34. saveHosts(svr, list)
  35. .then(() => {
  36. notify(svr, 'SwitchHosts!', 'OK')
  37. svr.broadcast('reload')
  38. res.end('toggle:' + id)
  39. })
  40. })
  41. .catch(e => {
  42. res.end(e.toString())
  43. })
  44. }