improving by extracting common userID method
This commit is contained in:
@ -30,17 +30,27 @@ type StackHandler struct {
|
||||
stackModel models.ListModel
|
||||
}
|
||||
|
||||
func (h *StackHandler) getAllStacks(w http.ResponseWriter, r *http.Request) {
|
||||
func (h *StackHandler) withUserID(
|
||||
fn func(userID uuid.UUID, w http.ResponseWriter, r *http.Request),
|
||||
) func(w http.ResponseWriter, r *http.Request) {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
userID, err := middleware.GetUserID(ctx)
|
||||
if err != nil {
|
||||
h.logger.Warn("could not get users in get all stacks", "err", err)
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
fn(userID, w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *StackHandler) getAllStacks(userID uuid.UUID, w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
userId, err := middleware.GetUserID(ctx)
|
||||
if err != nil {
|
||||
h.logger.Warn("could not get users in get all stacks", "err", err)
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
lists, err := h.stackModel.List(ctx, userId)
|
||||
lists, err := h.stackModel.List(ctx, userID)
|
||||
if err != nil {
|
||||
h.logger.Warn("could not get stacks", "err", err)
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
@ -50,16 +60,9 @@ func (h *StackHandler) getAllStacks(w http.ResponseWriter, r *http.Request) {
|
||||
writeJsonOrError(h.logger, lists, w)
|
||||
}
|
||||
|
||||
func (h *StackHandler) getStackItems(w http.ResponseWriter, r *http.Request) {
|
||||
func (h *StackHandler) getStackItems(userID uuid.UUID, w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
_, err := middleware.GetUserID(ctx)
|
||||
if err != nil {
|
||||
h.logger.Warn("could not get users in get all stacks", "err", err)
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
listID := r.PathValue("listID")
|
||||
if len(listID) == 0 {
|
||||
h.logger.Warn("listID is not present in path")
|
||||
@ -93,8 +96,8 @@ func (h *StackHandler) CreateRoutes(r chi.Router) {
|
||||
r.Use(middleware.ProtectedRoute)
|
||||
r.Use(middleware.SetJson)
|
||||
|
||||
r.Get("/", h.getAllStacks)
|
||||
r.Get("/{listID}", h.getStackItems)
|
||||
r.Get("/", h.withUserID(h.getAllStacks))
|
||||
r.Get("/{listID}", h.withUserID(h.getStackItems))
|
||||
})
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user