posts.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. const router = require('express').Router()
  2. import { Post } from '../db/models'
  3. router.get('/', async (req: any, res: any, next: any) => {
  4. try {
  5. Post.findAll().then((p: any) => res.json(p))
  6. //Post.findAllWithIncludes().then((p: any) => res.json(p))
  7. } catch (err) {
  8. next(err)
  9. }
  10. })
  11. router.get('/:id', async (req: any, res: any, next: any) => {
  12. try {
  13. Post.findByIdWithIncludes(req.params.id).then((p: any) => res.json(p))
  14. } catch (err) {
  15. next(err)
  16. }
  17. })
  18. router.post('/', async (req: any, res: any, next: any) => {
  19. try {
  20. Post.create(req.body).then((post: any) =>
  21. Post.findByIdWithIncludes(post.id).then((p: any) => res.json(p))
  22. )
  23. } catch (err) {
  24. next(err)
  25. }
  26. })
  27. router.put('/:id', async (req: any, res: any, next: any) => {
  28. try {
  29. Post.findByPk(req.params.id).then((post: any) =>
  30. post
  31. .update(req.body)
  32. .then(() =>
  33. Post.findByIdWithIncludes(req.params.id).then((p: any) =>
  34. res.json(p)
  35. )
  36. )
  37. )
  38. } catch (err) {
  39. next(err)
  40. }
  41. })
  42. router.post('/:id/delete', async (req: any, res: any, next: any) => {
  43. try {
  44. //Post.findByPk(req.params.id).then((post:any)=>res.json(post.delete())
  45. } catch (err) {
  46. next(err)
  47. }
  48. })
  49. module.exports = router