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.

56 lines
1.3 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/docs.json', 'utf8'))
  5. // Get doc 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 doc.
  15. router.post('/', (req, res) => {
  16. const doc = {
  17. id: db.reduce((x, y) => { return x.id > y.id ? x : y }).id + 1,
  18. text: req.body.text
  19. }
  20. res.json(doc)
  21. })
  22. // Get a doc.
  23. router.get('/:docId', (req, res) => {
  24. const doc = db.find(item => item.id === parseInt(req.params.docId))
  25. if (doc) {
  26. res.json(doc)
  27. } else {
  28. res.status(404).json({ detail: 'Not found.' })
  29. }
  30. })
  31. // Update a doc.
  32. router.put('/:docId', (req, res) => {
  33. const docIndex = db.findIndex(item => item.id === parseInt(req.params.docId))
  34. if (docIndex !== -1) {
  35. db[docIndex] = req.body
  36. res.json(db[docIndex])
  37. } else {
  38. res.status(404).json({ detail: 'Not found.' })
  39. }
  40. })
  41. // Delete a doc.
  42. router.delete('/:docId', (req, res, next) => {
  43. const doc = db.find(item => item.id === parseInt(req.params.docId))
  44. if (doc) {
  45. db = db.filter(item => item.id !== parseInt(req.params.docId))
  46. res.json(doc)
  47. } else {
  48. res.status(404).json({ detail: 'Not found.' })
  49. }
  50. })
  51. module.exports = router