Can create new blogs

This commit is contained in:
cdricms
2025-02-21 19:46:36 +01:00
parent 7a97961fef
commit 4b005945b2
9 changed files with 362 additions and 99 deletions

View File

@@ -7,6 +7,8 @@ import (
core "fr.latosa-escrima/core"
"fr.latosa-escrima/core/models"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
)
func HandleNew(w http.ResponseWriter, r *http.Request) {
@@ -18,11 +20,44 @@ func HandleNew(w http.ResponseWriter, r *http.Request) {
}.Respond(w, http.StatusBadRequest)
}
if _, err := core.DB.NewInsert().Model(&blog).Exec(context.Background()); err != nil {
token, ok := r.Context().Value("token").(*jwt.Token)
if !ok {
core.JSONError{
Status: core.Error,
Message: "Couldn't retrieve your JWT.",
}.Respond(w, http.StatusInternalServerError)
return
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
core.JSONError{
Status: core.Error,
Message: "Invalid token claims.",
}.Respond(w, http.StatusInternalServerError)
return
}
id := claims["user_id"].(string)
author_uuid, err := uuid.Parse(id)
if err != nil {
core.JSONError{
Status: core.Error,
Message: "Invalid token claims.",
}.Respond(w, http.StatusInternalServerError)
return
}
blog.AuthorID = author_uuid
if _, err := core.DB.NewInsert().
Model(&blog).
Exec(context.Background()); err != nil {
core.JSONError{
Status: core.Error,
Message: err.Error(),
}.Respond(w, http.StatusNotAcceptable)
return
}
core.JSONSuccess{

View File

@@ -0,0 +1,19 @@
package migrations
import (
"context"
"fmt"
"github.com/uptrace/bun"
)
func init() {
Migrations.MustRegister(func(ctx context.Context, db *bun.DB) error {
fmt.Print(" [up migration] ")
_, err := db.Exec(`ALTER TABLE blogs ALTER COLUMN blog_id SET DEFAULT gen_random_uuid()`)
return err
}, func(ctx context.Context, db *bun.DB) error {
fmt.Print(" [down migration] ")
return nil
})
}

View File

@@ -10,7 +10,7 @@ import (
type Blog struct {
bun.BaseModel `bun:"table:blogs"`
BlogID uuid.UUID `bun:"type:uuid,pk,default:gen_random_uuid()" json:"blogID"`
BlogID uuid.UUID `bun:"blog_id,type:uuid,pk,default:gen_random_uuid()" json:"blogID"`
Slug string `bun:"slug,unique,notnull" json:"slug"`
Content string `bun:"content,notnull" json:"content"`
Title string `bun:"title,notnull" json:"title"`