You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.8 KiB

5 years ago
5 years ago
5 years ago
  1. const fs = require('fs')
  2. const bodyParser = require('body-parser')
  3. const express = require('express')
  4. const router = express.Router()
  5. let db = JSON.parse(fs.readFileSync('./api/db/members.json', 'utf8'))
  6. const users = JSON.parse(fs.readFileSync('./api/db/users.json', 'utf8'))
  7. router.use(bodyParser.json())
  8. router.use(bodyParser.urlencoded({ extended: true }))
  9. // Get project user list.
  10. router.get('/', (req, res) => {
  11. const q = req.query.q
  12. if (q) {
  13. res.json(db.filter(item => item.name.toLowerCase().includes(q.toLowerCase())))
  14. } else {
  15. res.json(db)
  16. }
  17. })
  18. // Add a project user.
  19. router.post('/', (req, res) => {
  20. const user = users.find(item => item.id === parseInt(req.body.id, 10))
  21. const member = {
  22. ...user,
  23. role: req.body.role
  24. }
  25. db.push(member)
  26. res.json(member)
  27. })
  28. // Update a project user.
  29. router.put('/:userId', (req, res) => {
  30. const projectIndex = db.findIndex(item => item.id === parseInt(req.params.userId, 10))
  31. if (projectIndex !== -1) {
  32. db[projectIndex] = req.body
  33. res.json(db[projectIndex])
  34. } else {
  35. res.status(404).json({ detail: 'Not found.' })
  36. }
  37. })
  38. // Partially update a project user.
  39. router.patch('/:userId', (req, res) => {
  40. const projectIndex = db.findIndex(item => item.id === parseInt(req.params.userId, 10))
  41. if (projectIndex !== -1) {
  42. db[projectIndex].role = req.body.role
  43. res.json(db[projectIndex])
  44. } else {
  45. res.status(404).json({ detail: 'Not found.' })
  46. }
  47. })
  48. // Delete a project user.
  49. router.delete('/:userId', (req, res, next) => {
  50. const project = db.find(item => item.id === parseInt(req.params.userId, 10))
  51. if (project) {
  52. db = db.filter(item => item.id !== parseInt(req.params.userId, 10))
  53. res.json(project)
  54. } else {
  55. res.status(404).json({ detail: 'Not found.' })
  56. }
  57. })
  58. module.exports = router