category.js 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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) => {
  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'] },
  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) {
  97. if(e.name === 'invalidParameter') {
  98. res.status(400)
  99. res.json({
  100. errors: [e]
  101. })
  102. } else {
  103. console.log(e)
  104. res.status(500)
  105. res.json({
  106. errors: [Errors.unknown]
  107. })
  108. }
  109. }
  110. })
  111. router.all('*', (req, res, next) => {
  112. if(!req.session.loggedIn || !req.session.admin) {
  113. res.status(401)
  114. res.json({
  115. errors: [Errors.requestNotAuthorized]
  116. })
  117. } else {
  118. next()
  119. }
  120. })
  121. router.post('/', async (req, res) => {
  122. try {
  123. let category = await Category.create({
  124. name: req.body.name
  125. })
  126. res.json(category.toJSON())
  127. } catch (e) {
  128. if(e.name === 'SequelizeUniqueConstraintError') {
  129. res.status(400)
  130. res.json({
  131. errors: [Errors.categoryAlreadyExists]
  132. })
  133. } else if(e instanceof Sequelize.ValidationError) {
  134. res.status(400)
  135. res.json(e)
  136. } else {
  137. console.log(e)
  138. res.status(500)
  139. res.json({
  140. errors: [Errors.unknown]
  141. })
  142. }
  143. }
  144. })
  145. module.exports = router