config.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. const asyncWrapper = require('../middleware/asyncWrapper');
  2. const ErrorResponse = require('../utils/ErrorResponse');
  3. const Config = require('../models/Config');
  4. // @desc Insert new key:value pair
  5. // @route POST /api/config
  6. // @access Public
  7. exports.createPair = asyncWrapper(async (req, res, next) => {
  8. const pair = await Config.create(req.body);
  9. res.status(201).json({
  10. success: true,
  11. data: pair
  12. })
  13. })
  14. // @desc Get all key:value pairs
  15. // @route GET /api/config
  16. // @access Public
  17. exports.getAllPairs = asyncWrapper(async (req, res, next) => {
  18. const pairs = await Config.findAll();
  19. res.status(201).json({
  20. success: true,
  21. data: pairs
  22. })
  23. })
  24. // @desc Get single key:value pair
  25. // @route GET /api/config/:key
  26. // @access Public
  27. exports.getSinglePair = asyncWrapper(async (req, res, next) => {
  28. const pair = await Config.findOne({
  29. where: { key: req.params.key }
  30. });
  31. if (!pair) {
  32. return next(new ErrorResponse(`Key ${req.params.key} was not found`, 404));
  33. }
  34. res.status(201).json({
  35. success: true,
  36. data: pair
  37. })
  38. })
  39. // @desc Update value
  40. // @route PUT /api/config/:key
  41. // @access Public
  42. exports.updateValue = asyncWrapper(async (req, res, next) => {
  43. let pair = await Config.findOne({
  44. where: { key: req.params.key }
  45. });
  46. if (!pair) {
  47. return next(new ErrorResponse(`Key ${req.params.key} was not found`, 404));
  48. }
  49. if (pair.isLocked) {
  50. return next(new ErrorResponse(`Value of key ${req.params.key} is locked and can not be changed`, 400));
  51. }
  52. pair = await pair.update({ ...req.body });
  53. res.status(200).json({
  54. success: true,
  55. data: pair
  56. })
  57. })
  58. // @desc Delete key:value pair
  59. // @route DELETE /api/config/:key
  60. // @access Public
  61. exports.deletePair = asyncWrapper(async (req, res, next) => {
  62. const pair = await Config.findOne({
  63. where: { key: req.params.key }
  64. });
  65. if (!pair) {
  66. return next(new ErrorResponse(`Key ${req.params.key} was not found`, 404));
  67. }
  68. if (pair.isLocked) {
  69. return next(new ErrorResponse(`Value of key ${req.params.key} is locked and can not be deleted`, 400));
  70. }
  71. await pair.destroy();
  72. res.status(200).json({
  73. success: true,
  74. data: {}
  75. })
  76. })