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.

63 lines
1.6 KiB

  1. const fs = require('fs')
  2. const express = require('express')
  3. const router = express.Router()
  4. let db = JSON.parse(fs.readFileSync('./api/db/labels.json', 'utf8'))
  5. // Get label list.
  6. router.get('/', (req, res) => {
  7. const q = req.query.q
  8. if (q) {
  9. res.json(db.filter(item => item.text.toLowerCase().includes(q.toLowerCase())))
  10. } else {
  11. res.json(db)
  12. }
  13. })
  14. // Create a label.
  15. router.post('/', (req, res) => {
  16. const label = {
  17. id: db.reduce((x, y) => { return x.id > y.id ? x : y }).id + 1,
  18. text: req.body.text,
  19. prefix_key: req.body.prefix_key,
  20. suffix_key: req.body.suffix_key,
  21. background_color: req.body.background_color,
  22. text_color: '#ffffff'
  23. }
  24. db.push(label)
  25. res.json(label)
  26. })
  27. // Get a label.
  28. router.get('/:labelId', (req, res) => {
  29. const label = db.find(item => item.id === parseInt(req.params.labelId, 10))
  30. if (label) {
  31. res.json(label)
  32. } else {
  33. res.status(404).json({ detail: 'Not found.' })
  34. }
  35. })
  36. // Update a label.
  37. router.patch('/:labelId', (req, res) => {
  38. const labelIndex = db.findIndex(item => item.id === parseInt(req.params.labelId, 10))
  39. if (labelIndex !== -1) {
  40. // db[labelIndex] = req.body
  41. Object.assign(db[labelIndex], req.body)
  42. res.json(db[labelIndex])
  43. } else {
  44. res.status(404).json({ detail: 'Not found.' })
  45. }
  46. })
  47. // Delete a label.
  48. router.delete('/:labelId', (req, res, next) => {
  49. const label = db.find(item => item.id === parseInt(req.params.labelId, 10))
  50. if (label) {
  51. db = db.filter(item => item.id !== parseInt(req.params.labelId, 10))
  52. res.json(label)
  53. } else {
  54. res.status(404).json({ detail: 'Not found.' })
  55. }
  56. })
  57. module.exports = router