Merge remote-tracking branch 'origin/dev/guerby' into dev/cedric

This commit is contained in:
cdricms
2025-01-15 15:45:39 +01:00
10 changed files with 207 additions and 82 deletions

View File

@@ -0,0 +1,87 @@
package core
import (
"encoding/json"
"net/http"
)
type JSONStatus string
const (
Error JSONStatus = "Error"
Success JSONStatus = "Success"
)
type JSONResponse interface {
ToJSON() ([]byte, error)
Respond(w http.ResponseWriter, code int)
}
type JSONError struct {
Status JSONStatus `json:"status"`
Message string `json:"message"`
}
type JSONSuccess struct {
Status JSONStatus `json:"status"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
func (r *JSONError) ToJSON() ([]byte, error) {
return json.Marshal(r)
}
func (r *JSONSuccess) ToJSON() ([]byte, error) {
return json.Marshal(r)
}
func defaultResponse(r JSONResponse, w http.ResponseWriter, code int) {
jsonData, err := r.ToJSON()
if err != nil {
http.Error(w, err.Error(), http.StatusNotAcceptable)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(jsonData)
}
func (r JSONError) Respond(w http.ResponseWriter, code int) {
defaultResponse(&r, w, code)
}
func (r JSONSuccess) Respond(w http.ResponseWriter, code int) {
defaultResponse(&r, w, code)
}
func HandleMiddlewareRoute(pattern string,
handler func(w http.ResponseWriter, r *http.Request),
middleware func(http.Handler) http.Handler,
mux *http.ServeMux,
) {
// mux.HandleFunc(pattern, handler)
mux.Handle(pattern, middleware(http.HandlerFunc(handler)))
}
type HandlerFunc func(w http.ResponseWriter, r *http.Request)
type Handler struct {
Handler HandlerFunc
Middleware func(http.Handler) http.Handler
}
func HandleRoutes(mux *http.ServeMux, routes map[string]Handler) {
for pattern, handler := range routes {
if handler.Middleware == nil {
mux.HandleFunc(pattern, handler.Handler)
} else {
HandleMiddlewareRoute(
pattern,
handler.Handler,
handler.Middleware,
mux,
)
}
}
}

110
backend/api/core/schemas.go Normal file
View File

@@ -0,0 +1,110 @@
package core
import (
"context"
"database/sql"
"fmt"
"time"
"github.com/google/uuid"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/pgdialect"
"github.com/uptrace/bun/driver/pgdriver"
)
var DB *bun.DB
type DSN struct {
Hostname string
Port string
DBName string
User string
Password string
}
func (dsn *DSN) ToString() string {
return fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=disable", dsn.User, dsn.Password, dsn.Hostname, dsn.Port, dsn.DBName)
}
type Role string
const (
AdminRole Role = "admin"
UserRole Role = "user"
)
type User struct {
bun.BaseModel `bun:"table:users"`
UserID uuid.UUID `bun:"type:uuid,pk,default:gen_random_uuid()"`
FirstName string `bun:"firstname,notnull"`
LastName string `bun:"lastname,notnull"`
Email string `bun:"email,unique,notnull"`
Password string `bun:"password,notnull"`
Phone string `bun:"phone,notnull"`
Role Role `bun:"role,notnull,default:'user'"`
CreatedAt time.Time `bun:"created_at,default:current_timestamp"`
UpdatedAt time.Time `bun:"updated_at,default:current_timestamp"`
Events []Event `bun:"m2m:events_to_users,join:User=Event"`
Articles []*Blog `bun:"rel:has-many,join:user_id=blog_id"`
}
type Event struct {
bun.BaseModel `bun:"table:events"`
EventID uuid.UUID `bun:"type:uuid,pk"`
CreationDate time.Time `bun:"creation_date,notnull,default:current_timestamp"`
ScheduleStart time.Time `bun:"schedule_start,notnull"`
ScheduleEnd time.Time `bun:"schedule_end,notnull"`
Status string `bun:"status,notnull"`
}
type EventToUser struct {
bun.BaseModel `bun:"table:events_to_users"`
EventID uuid.UUID `bun:"type:uuid,pk"`
UserID uuid.UUID `bun:"type:uuid,pk"`
Event *Event `bun:"rel:belongs-to,join:event_id=event_id"`
User *User `bun:"rel:belongs-to,join:user_id=user_id"`
}
type Blog struct {
bun.BaseModel `bun:"table:blogs"`
BlogID uuid.UUID `bun:"type:uuid,pk"`
Slug string `bun:"slug,unique,notnull"`
Content string `bun:"content,notnull"`
Label string `bun:"label"`
AuthorID uuid.UUID `bun:"author_id,notnull"`
Published time.Time `bun:"published,default:current_timestamp"`
Summary string `bun:"summary"`
Image string `bun:"image"`
Href string `bun:"href"`
Author *User `bun:"rel:belongs-to,join:author_id=user_id"`
}
type WebsiteSettings struct {
bun.BaseModel `bun:"table:website_settings"`
ID uuid.UUID `bun:"type:uuid,pk,default:gen_random_uuid()"`
AutoAcceptDemand bool `bun:"auto_accept_demand,default:false"`
}
func InitDatabase(dsn DSN) (*bun.DB, error) {
sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn.ToString())))
db := bun.NewDB(sqldb, pgdialect.New())
db.RegisterModel((*EventToUser)(nil))
_, err := db.NewCreateTable().Model((*User)(nil)).IfNotExists().Exec(context.Background())
_, err = db.NewCreateTable().Model((*Event)(nil)).IfNotExists().Exec(context.Background())
_, err = db.NewCreateTable().Model((*EventToUser)(nil)).IfNotExists().Exec(context.Background())
_, err = db.NewCreateTable().Model((*Blog)(nil)).IfNotExists().Exec(context.Background())
_, err = db.NewCreateTable().Model((*WebsiteSettings)(nil)).IfNotExists().Exec(context.Background())
if err != nil {
return nil, err
}
return db, nil
}