From 568ffd16150acfafae5f96388ab99e272b887ccf Mon Sep 17 00:00:00 2001 From: Masahiko AMANO Date: Mon, 6 Jan 2025 16:11:35 +0300 Subject: [PATCH] init(api): add quote add handler --- backend/api/handlers.go | 43 +++++++++++++++++++++++++++++++++++++++++ backend/api/routes.go | 1 + 2 files changed, 44 insertions(+) diff --git a/backend/api/handlers.go b/backend/api/handlers.go index 9effb8a..0d4be0d 100644 --- a/backend/api/handlers.go +++ b/backend/api/handlers.go @@ -105,4 +105,47 @@ func quoteGet(c *gin.Context) { c.JSON(http.StatusOK, quote) } +func quoteAdd(c *gin.Context) { + session := sessions.Default(c) + user_id, ok := session.Get("user_id").(string) + if !ok { + c.JSON(http.StatusUnauthorized, gin.H{"error": "Ты это, залогинься сначала что ли, а то чё как крыса"}) + return + } + var body map[string]string + err := c.BindJSON(&body) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "И чё за шнягу ты мне кинул?"}) + return + } + text, ok := body["text"] + if !ok || text == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "Э, а где цитата?"}) + return + } + author, ok := body["author"] + if !ok || author == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "Цитата может быть сказана только тем, кто её сказанул! А кто сказанул эту цитату?"}) + return + } + var datetime time.Time + datetimeStr, ok := body["datetime"] + if ok { + datetime, err = time.Parse(time.RFC3339, datetimeStr) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "Чёт дата и время у тебя какие-то кривые..."}) + return + } + } else { + datetime = time.Now() + } + quote, err := db.QuoteAdd(context.Background(), user_id, text, author, datetime) + if err != nil { + status, message := HandleDBError(err) + c.JSON(status, gin.H{"error": message}) + return + } + c.JSON(http.StatusCreated, quote) +} + //#endregion Quotes diff --git a/backend/api/routes.go b/backend/api/routes.go index 08f8ba6..b7daca2 100644 --- a/backend/api/routes.go +++ b/backend/api/routes.go @@ -22,6 +22,7 @@ func RegisterRoutes(r *gin.Engine) { { api.POST("/auth", userAuth) api.GET("/quotes", quotesGet) + api.POST("/quotes", quoteAdd) api.GET("/quotes/:id", quoteGet) } }