category.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Copyright 2017 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package api // import "miniflux.app/api"
  5. import (
  6. "errors"
  7. "net/http"
  8. "miniflux.app/http/request"
  9. "miniflux.app/http/response/json"
  10. )
  11. // CreateCategory is the API handler to create a new category.
  12. func (c *Controller) CreateCategory(w http.ResponseWriter, r *http.Request) {
  13. category, err := decodeCategoryPayload(r.Body)
  14. if err != nil {
  15. json.BadRequest(w, err)
  16. return
  17. }
  18. userID := request.UserID(r)
  19. category.UserID = userID
  20. if err := category.ValidateCategoryCreation(); err != nil {
  21. json.BadRequest(w, err)
  22. return
  23. }
  24. if c, err := c.store.CategoryByTitle(userID, category.Title); err != nil || c != nil {
  25. json.BadRequest(w, errors.New("This category already exists"))
  26. return
  27. }
  28. err = c.store.CreateCategory(category)
  29. if err != nil {
  30. json.ServerError(w, err)
  31. return
  32. }
  33. json.Created(w, category)
  34. }
  35. // UpdateCategory is the API handler to update a category.
  36. func (c *Controller) UpdateCategory(w http.ResponseWriter, r *http.Request) {
  37. categoryID := request.RouteInt64Param(r, "categoryID")
  38. category, err := decodeCategoryPayload(r.Body)
  39. if err != nil {
  40. json.BadRequest(w, err)
  41. return
  42. }
  43. category.UserID = request.UserID(r)
  44. category.ID = categoryID
  45. if err := category.ValidateCategoryModification(); err != nil {
  46. json.BadRequest(w, err)
  47. return
  48. }
  49. err = c.store.UpdateCategory(category)
  50. if err != nil {
  51. json.ServerError(w, err)
  52. return
  53. }
  54. json.Created(w, category)
  55. }
  56. // GetCategories is the API handler to get a list of categories for a given user.
  57. func (c *Controller) GetCategories(w http.ResponseWriter, r *http.Request) {
  58. categories, err := c.store.Categories(request.UserID(r))
  59. if err != nil {
  60. json.ServerError(w, err)
  61. return
  62. }
  63. json.OK(w, r, categories)
  64. }
  65. // RemoveCategory is the API handler to remove a category.
  66. func (c *Controller) RemoveCategory(w http.ResponseWriter, r *http.Request) {
  67. userID := request.UserID(r)
  68. categoryID := request.RouteInt64Param(r, "categoryID")
  69. if !c.store.CategoryExists(userID, categoryID) {
  70. json.NotFound(w, errors.New("Category not found"))
  71. return
  72. }
  73. if err := c.store.RemoveCategory(userID, categoryID); err != nil {
  74. json.ServerError(w, err)
  75. return
  76. }
  77. json.NoContent(w)
  78. }