category.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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, r, err)
  16. return
  17. }
  18. userID := request.UserID(r)
  19. category.UserID = userID
  20. if err := category.ValidateCategoryCreation(); err != nil {
  21. json.BadRequest(w, r, err)
  22. return
  23. }
  24. if c, err := c.store.CategoryByTitle(userID, category.Title); err != nil || c != nil {
  25. json.BadRequest(w, r, errors.New("This category already exists"))
  26. return
  27. }
  28. if err := c.store.CreateCategory(category); err != nil {
  29. json.ServerError(w, r, err)
  30. return
  31. }
  32. json.Created(w, r, category)
  33. }
  34. // UpdateCategory is the API handler to update a category.
  35. func (c *Controller) UpdateCategory(w http.ResponseWriter, r *http.Request) {
  36. categoryID := request.RouteInt64Param(r, "categoryID")
  37. category, err := decodeCategoryPayload(r.Body)
  38. if err != nil {
  39. json.BadRequest(w, r, err)
  40. return
  41. }
  42. category.UserID = request.UserID(r)
  43. category.ID = categoryID
  44. if err := category.ValidateCategoryModification(); err != nil {
  45. json.BadRequest(w, r, err)
  46. return
  47. }
  48. err = c.store.UpdateCategory(category)
  49. if err != nil {
  50. json.ServerError(w, r, err)
  51. return
  52. }
  53. json.Created(w, r, category)
  54. }
  55. // GetCategories is the API handler to get a list of categories for a given user.
  56. func (c *Controller) GetCategories(w http.ResponseWriter, r *http.Request) {
  57. categories, err := c.store.Categories(request.UserID(r))
  58. if err != nil {
  59. json.ServerError(w, r, err)
  60. return
  61. }
  62. json.OK(w, r, categories)
  63. }
  64. // RemoveCategory is the API handler to remove a category.
  65. func (c *Controller) RemoveCategory(w http.ResponseWriter, r *http.Request) {
  66. userID := request.UserID(r)
  67. categoryID := request.RouteInt64Param(r, "categoryID")
  68. if !c.store.CategoryExists(userID, categoryID) {
  69. json.NotFound(w, r)
  70. return
  71. }
  72. if err := c.store.RemoveCategory(userID, categoryID); err != nil {
  73. json.ServerError(w, r, err)
  74. return
  75. }
  76. json.NoContent(w, r)
  77. }