category.js 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. let express = require('express')
  2. let router = express.Router()
  3. const Errors = require('../lib/errors')
  4. let pagination = require('../lib/pagination')
  5. let { Category, Post, Thread, User, Sequelize } = require('../models')
  6. router.get('/', async (req, res) => {
  7. try {
  8. let categories = await Category.findAll()
  9. res.json(categories)
  10. } catch (e) {
  11. res.status(500)
  12. res.json({
  13. errors: [Errors.unknown]
  14. })
  15. }
  16. })
  17. router.get('/:category', async (req, res, next) => {
  18. try {
  19. let threads, threadsLatestPost, resThreads, user
  20. let { from, limit } = pagination.getPaginationProps(req.query, true)
  21. if(req.query.username) {
  22. user = await User.findOne({ where: { username: req.query.username }})
  23. }
  24. function threadInclude(order) {
  25. let options = {
  26. model: Thread,
  27. order: [['id', 'DESC']],
  28. limit,
  29. where: {},
  30. include: [
  31. Category,
  32. { model: User, attributes: ['username', 'createdAt', 'id', 'color', 'picture'] },
  33. {
  34. model: Post, limit: 1, order: [['id', order]], include:
  35. [{ model: User, attributes: ['username', 'id'] }]
  36. }
  37. ]
  38. }
  39. if(user) {
  40. options.where.userId = user.id
  41. }
  42. if(from !== null) {
  43. options.where.id = { $lte: from }
  44. }
  45. return [options]
  46. }
  47. if(req.params.category === 'ALL') {
  48. threads = await Thread.findAll( threadInclude('ASC')[0] )
  49. threadsLatestPost = await Thread.findAll( threadInclude('DESC')[0] )
  50. } else {
  51. threads = await Category.findOne({
  52. where: { value: req.params.category },
  53. include: threadInclude('ASC')
  54. })
  55. threadsLatestPost = await Category.findOne({
  56. where: { value: req.params.category },
  57. include: threadInclude('DESC')
  58. })
  59. }
  60. if(!threads) throw Errors.invalidParameter('id', 'category does not exist')
  61. if(Array.isArray(threads)) {
  62. resThreads = {
  63. name: 'All',
  64. value: 'ALL',
  65. Threads: threads,
  66. meta: {}
  67. }
  68. threadsLatestPost = { Threads: threadsLatestPost }
  69. } else {
  70. resThreads = threads.toJSON()
  71. resThreads.meta = {}
  72. }
  73. threadsLatestPost.Threads.forEach((thread, i) => {
  74. let first = resThreads.Threads[i].Posts[0]
  75. let latest = thread.Posts[0]
  76. if(first.id === latest.id) return
  77. resThreads.Threads[i].Posts.push(latest)
  78. })
  79. let nextId = await pagination.getNextIdDesc(Thread, user ? { userId: user.id } : {}, resThreads.Threads)
  80. if(nextId) {
  81. resThreads.meta.nextURL =
  82. `/api/v1/category/${req.params.category}?&limit=${limit}&from=${nextId - 1}`
  83. if(user) {
  84. resThreads.meta.nextURL += '&username=' + user.username
  85. }
  86. resThreads.meta.nextThreadsCount = await pagination.getNextCount(
  87. Thread, resThreads.Threads, limit,
  88. user ? { userId: user.id } : {},
  89. true
  90. )
  91. } else {
  92. resThreads.meta.nextURL = null
  93. resThreads.meta.nextThreadsCount = 0
  94. }
  95. res.json(resThreads)
  96. } catch (e) { next(e) }
  97. })
  98. router.all('*', (req, res, next) => {
  99. if(!req.session.admin) {
  100. res.status(401)
  101. res.json({
  102. errors: [Errors.requestNotAuthorized]
  103. })
  104. } else {
  105. next()
  106. }
  107. })
  108. router.post('/', async (req, res, next) => {
  109. try {
  110. let category = await Category.create({
  111. name: req.body.name,
  112. color: req.body.color
  113. })
  114. res.json(category.toJSON())
  115. } catch (e) {
  116. if(e.name === 'SequelizeUniqueConstraintError') {
  117. res.status(400)
  118. res.json({
  119. errors: [Errors.categoryAlreadyExists]
  120. })
  121. } else {
  122. next(e)
  123. }
  124. }
  125. })
  126. router.put('/:category_id', async (req, res, next) => {
  127. try {
  128. let id = req.params.category_id
  129. let obj = {}
  130. if(req.body.color) obj.color = req.body.color
  131. if(req.body.name) obj.name = req.body.name
  132. let affectedRows = await Category.update(obj, {
  133. where: { id }
  134. })
  135. if(!affectedRows[0]) {
  136. throw Errors.sequelizeValidation(Sequelize, {
  137. error: 'category id is not valid',
  138. value: id
  139. })
  140. } else {
  141. let ret = await Category.findById(id)
  142. res.json(ret.toJSON())
  143. }
  144. } catch(e) { next(e) }
  145. })
  146. router.delete('/:id', async (req, res, next) => {
  147. try {
  148. let category = await Category.findById(req.params.id)
  149. if(!category) throw Errors.sequelizeValidation(Sequelize, {
  150. error: 'category id does not exist',
  151. value: req.params.id
  152. })
  153. let otherCategory = await Category.findOrCreate({
  154. where: { name: 'Other' },
  155. defaults: { color: '#9a9a9a' }
  156. })
  157. let up = await Thread.update({ CategoryId: otherCategory[0].id }, {
  158. where: { CategoryId: req.params.id }
  159. })
  160. await category.destroy()
  161. res.json({
  162. success: true,
  163. otherCategoryCreated: otherCategory[1] ? otherCategory[0] : null
  164. })
  165. } catch (e) { next(e) }
  166. })
  167. module.exports = router