category.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. color: req.body.color
  126. })
  127. res.json(category.toJSON())
  128. } catch (e) {
  129. if(e.name === 'SequelizeUniqueConstraintError') {
  130. res.status(400)
  131. res.json({
  132. errors: [Errors.categoryAlreadyExists]
  133. })
  134. } else if(e instanceof Sequelize.ValidationError) {
  135. res.status(400)
  136. res.json(e)
  137. } else {
  138. console.log(e)
  139. res.status(500)
  140. res.json({
  141. errors: [Errors.unknown]
  142. })
  143. }
  144. }
  145. })
  146. router.put('/:category_id', async (req, res) => {
  147. try {
  148. let id = req.params.category_id
  149. let obj = {}
  150. if(req.body.color) obj.color = req.body.color
  151. if(req.body.name) obj.name = req.body.name
  152. let affectedRows = await Category.update(obj, {
  153. where: { id }
  154. })
  155. if(!affectedRows[0]) {
  156. throw Errors.sequelizeValidation(Sequelize, {
  157. error: 'category id is not valid',
  158. value: id
  159. })
  160. } else {
  161. let ret = await Category.findById(id)
  162. res.json(ret.toJSON())
  163. }
  164. } catch(e) {
  165. if(e instanceof Sequelize.ValidationError) {
  166. res.status(400)
  167. res.json(e)
  168. } else {
  169. console.log(e)
  170. res.status(500)
  171. res.json({
  172. errors: [Errors.unknown]
  173. })
  174. }
  175. }
  176. })
  177. router.delete('/:id', async (req, res) => {
  178. try {
  179. let category = await Category.findById(req.params.id)
  180. if(!category) throw Errors.sequelizeValidation(Sequelize, {
  181. error: 'category id does not exist',
  182. value: req.params.id
  183. })
  184. let otherCategory = await Category.findOrCreate({
  185. where: { name: 'Other' },
  186. defaults: { color: '#9a9a9a' }
  187. })
  188. let up = await Thread.update({ CategoryId: otherCategory[0].id }, {
  189. where: { CategoryId: req.params.id }
  190. })
  191. await category.destroy()
  192. res.json({
  193. success: true,
  194. otherCategoryCreated: otherCategory[1] ? otherCategory[0] : null
  195. })
  196. } catch (e) {
  197. if(e instanceof Sequelize.ValidationError) {
  198. res.status(400)
  199. res.json(e)
  200. } else {
  201. console.log(e)
  202. res.status(500)
  203. res.json({
  204. errors: [Errors.unknown]
  205. })
  206. }
  207. }
  208. })
  209. module.exports = router