toggle.js 982 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 svr = require('../../svr')
  10. module.exports = (req, res) => {
  11. let id = req.param('id')
  12. let is_single
  13. getPref()
  14. .then(pref => {
  15. is_single = pref.choice_mode === 'single'
  16. })
  17. .then(() => getUserHosts())
  18. .then(list => {
  19. let item = list.find(i => i.id === id)
  20. if (!item) {
  21. res.end('not-found:' + id)
  22. return
  23. }
  24. item.on = !item.on
  25. if (item.on && is_single) {
  26. // 单选模式
  27. list.map(i => {
  28. if (i.id !== id) {
  29. i.on = false
  30. }
  31. })
  32. }
  33. saveHosts(svr, list)
  34. .then(() => {
  35. svr.broadcast('reload')
  36. res.end('toggle:' + id)
  37. })
  38. })
  39. .catch(e => {
  40. res.end(e.toString())
  41. })
  42. }