settings.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. let express = require('express')
  2. let router = express.Router()
  3. const Errors = require('../lib/errors')
  4. let { Settings } = require('../models')
  5. router.get('/', async (req, res) => {
  6. try {
  7. let settings = await Settings.get()
  8. if(!settings) throw Errors.noSettings
  9. res.json(settings.toJSON())
  10. } catch (e) {
  11. if(e === Errors.noSettings) {
  12. res.status(500)
  13. res.json({
  14. errors: [e]
  15. })
  16. } else {
  17. res.status(500)
  18. res.json({
  19. errors: [Errors.unknown]
  20. })
  21. }
  22. }
  23. })
  24. router.all('*', (req, res, next) => {
  25. if(req.session.admin) {
  26. next()
  27. } else {
  28. res.status(401)
  29. res.json({
  30. errors: [Errors.requestNotAuthorized]
  31. })
  32. }
  33. })
  34. router.put('/', async (req, res) => {
  35. let validationErrors = []
  36. let params = {}
  37. try {
  38. if(req.body.forumName !== undefined) {
  39. if(typeof req.body.forumName !== 'string') {
  40. validationErrors.push(Errors.invalidParameterType('forumName', 'string'))
  41. } else {
  42. params.forumName = req.body.forumName
  43. }
  44. }
  45. if(req.body.forumDescription !== undefined) {
  46. if(typeof req.body.forumDescription !== 'string') {
  47. validationErrors.push(Errors.invalidParameterType('forumDescription', 'string'))
  48. } else {
  49. params.forumDescription = req.body.forumDescription
  50. }
  51. }
  52. if(validationErrors.length) throw Errors.VALIDAITON_ERROR
  53. let updatedSettings = await Settings.set(params)
  54. res.json({
  55. forumName: req.body.forumName,
  56. forumDescription: req.body.forumDescription
  57. })
  58. } catch (e) {
  59. if(e === Errors.VALIDAITON_ERROR) {
  60. res.status(400)
  61. res.json({
  62. errors: [validationErrors]
  63. })
  64. } else {
  65. console.log(e)
  66. res.status(500)
  67. res.json({
  68. errors: [Errors.unknown]
  69. })
  70. }
  71. }
  72. })
  73. module.exports = router