init(api): add quote add handler

This commit is contained in:
Masahiko AMANO 2025-01-06 16:11:35 +03:00
parent 875452004d
commit 568ffd1615
2 changed files with 44 additions and 0 deletions

View File

@ -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

View File

@ -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)
}
}