category.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. func (h *handler) createCategory(w http.ResponseWriter, r *http.Request) {
  12. category, err := decodeCategoryPayload(r.Body)
  13. if err != nil {
  14. json.BadRequest(w, r, err)
  15. return
  16. }
  17. userID := request.UserID(r)
  18. category.UserID = userID
  19. if err := category.ValidateCategoryCreation(); err != nil {
  20. json.BadRequest(w, r, err)
  21. return
  22. }
  23. if c, err := h.store.CategoryByTitle(userID, category.Title); err != nil || c != nil {
  24. json.BadRequest(w, r, errors.New("This category already exists"))
  25. return
  26. }
  27. if err := h.store.CreateCategory(category); err != nil {
  28. json.ServerError(w, r, err)
  29. return
  30. }
  31. json.Created(w, r, category)
  32. }
  33. func (h *handler) updateCategory(w http.ResponseWriter, r *http.Request) {
  34. categoryID := request.RouteInt64Param(r, "categoryID")
  35. category, err := decodeCategoryPayload(r.Body)
  36. if err != nil {
  37. json.BadRequest(w, r, err)
  38. return
  39. }
  40. category.UserID = request.UserID(r)
  41. category.ID = categoryID
  42. if err := category.ValidateCategoryModification(); err != nil {
  43. json.BadRequest(w, r, err)
  44. return
  45. }
  46. err = h.store.UpdateCategory(category)
  47. if err != nil {
  48. json.ServerError(w, r, err)
  49. return
  50. }
  51. json.Created(w, r, category)
  52. }
  53. func (h *handler) getCategories(w http.ResponseWriter, r *http.Request) {
  54. categories, err := h.store.Categories(request.UserID(r))
  55. if err != nil {
  56. json.ServerError(w, r, err)
  57. return
  58. }
  59. json.OK(w, r, categories)
  60. }
  61. func (h *handler) removeCategory(w http.ResponseWriter, r *http.Request) {
  62. userID := request.UserID(r)
  63. categoryID := request.RouteInt64Param(r, "categoryID")
  64. if !h.store.CategoryExists(userID, categoryID) {
  65. json.NotFound(w, r)
  66. return
  67. }
  68. if err := h.store.RemoveCategory(userID, categoryID); err != nil {
  69. json.ServerError(w, r, err)
  70. return
  71. }
  72. json.NoContent(w, r)
  73. }