category.js 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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 } = require('../models')
  6. router.get('/', async (req, res) => {
  7. try {
  8. let categories = await Category.findAll({
  9. attributes: { exclude: ['id'] },
  10. include: Category.includeOptions('ASC', 1)
  11. })
  12. res.json(categories)
  13. } catch (e) {
  14. res.status(500)
  15. res.json({
  16. errors: [Errors.unknown]
  17. })
  18. }
  19. })
  20. router.get('/:category', async (req, res) => {
  21. try {
  22. let threads, threadsLatestPost, resThreads
  23. let { from, limit } = pagination.getPaginationProps(req.query)
  24. let where = {}
  25. if(req.query.username) where.username = req.query.username
  26. function concatenateThreads(threads) {
  27. let processedThreads = []
  28. threads.forEach(category => {
  29. let jsonCategory = category.toJSON()
  30. processedThreads.push(...jsonCategory.Threads)
  31. })
  32. return processedThreads
  33. }
  34. if(req.params.category === 'ALL') {
  35. threads = await Category.findAll({ where, include: Category.includeOptions('ASC') })
  36. threadsLatestPost = await Category.findAll({ where, include: Category.includeOptions('DESC') })
  37. } else {
  38. threads = await Category.findOne({
  39. where: { name: req.params.category },
  40. include: Category.includeOptions('ASC')
  41. })
  42. threadsLatestPost = await Category.findOne({
  43. where: { name: req.params.category },
  44. include: Category.includeOptions('DESC')
  45. })
  46. }
  47. if(!threads) throw Errors.invalidParameter('id', 'thread does not exist')
  48. if(Array.isArray(threads)) {
  49. resThreads = {
  50. name: 'All',
  51. value: 'ALL',
  52. Threads: concatenateThreads(threads),
  53. meta: {}
  54. }
  55. threadsLatestPost = { Threads: concatenateThreads(threadsLatestPost) }
  56. } else {
  57. resThreads = threads.toJSON()
  58. resThreads.meta = {}
  59. }
  60. threadsLatestPost.Threads.forEach((thread, i) => {
  61. let first = resThreads.Threads[i].Posts[0]
  62. let latest = thread.Posts[0]
  63. if(first.id === latest.id) return
  64. resThreads.Threads[i].Posts.push(latest)
  65. })
  66. let nextId = await pagination.getNextId(Thread, where, resThreads.Threads)
  67. if(nextId) {
  68. resThreads.meta.nextURL =
  69. `/api/v1/category/${req.params.category}?&limit=${limit}&from=${nextId}`
  70. if(req.query.username) {
  71. resThreads.meta.nextURL += '&username=' + req.query.username
  72. }
  73. resThreads.meta.nextThreadsCount = await pagination.getNextCount(
  74. Thread, resThreads.Threads, limit, where
  75. )
  76. } else {
  77. resThreads.meta.nextURL = null
  78. resThreads.meta.nextThreadsCount = 0
  79. }
  80. res.json(resThreads)
  81. } catch (e) {
  82. if(e.name === 'invalidParameter') {
  83. res.status(400)
  84. res.json({
  85. errors: [e]
  86. })
  87. } else {
  88. console.log(e)
  89. res.status(500)
  90. res.json({
  91. errors: [Errors.unknown]
  92. })
  93. }
  94. }
  95. })
  96. router.all('*', (req, res, next) => {
  97. if(!req.session.loggedIn || !req.session.admin) {
  98. res.status(401)
  99. res.json({
  100. errors: [Errors.requestNotAuthorized]
  101. })
  102. } else {
  103. next()
  104. }
  105. })
  106. router.post('/', async (req, res) => {
  107. let validationErrors = []
  108. try {
  109. if(req.body.name === undefined) {
  110. validationErrors.push(Errors.missingParameter('name'))
  111. } else if(typeof req.body.name !== 'string') {
  112. validationErrors.push(Errors.invalidParameterType('name', 'string'))
  113. } else if(!req.body.name.length) {
  114. validationErrors.push(Errors.parameterLengthTooSmall('name', '0'))
  115. }
  116. if(validationErrors.length) throw Errors.VALIDAITON_ERROR
  117. let category = await Category.create({
  118. name: req.body.name
  119. })
  120. res.json(category.toJSON())
  121. } catch (e) {
  122. if(e === Errors.VALIDAITON_ERROR) {
  123. res.status(400)
  124. res.json({
  125. errors: validationErrors
  126. })
  127. } else if(e.name === 'SequelizeUniqueConstraintError') {
  128. res.status(400)
  129. res.json({
  130. errors: [Errors.categoryAlreadyExists]
  131. })
  132. } else {
  133. res.status(500)
  134. res.json({
  135. errors: [Errors.unknown]
  136. })
  137. }
  138. }
  139. })
  140. module.exports = router