show first entry
This commit is contained in:
39
backend/blog/controller.go
Normal file
39
backend/blog/controller.go
Normal file
@ -0,0 +1,39 @@
|
||||
package blog
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/model"
|
||||
)
|
||||
|
||||
func (s Service) CreatePost(w http.ResponseWriter, r *http.Request) {
|
||||
var post model.Post
|
||||
if err := json.NewDecoder(r.Body).Decode(&post); err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
fmt.Fprint(w, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.db.Save(&post).Error; err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
fmt.Fprint(w, err.Error())
|
||||
}
|
||||
|
||||
json.NewEncoder(w).Encode(&post)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func (s Service) GetAllPosts(w http.ResponseWriter, r *http.Request) {
|
||||
var posts []model.Post
|
||||
|
||||
if err := s.db.Preload("Comments").Order("created_at DESC").Find(&posts).Error; err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
fmt.Fprint(w, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
json.NewEncoder(w).Encode(&posts)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
11
backend/blog/resource.go
Normal file
11
backend/blog/resource.go
Normal file
@ -0,0 +1,11 @@
|
||||
package blog
|
||||
|
||||
import "gorm.io/gorm"
|
||||
|
||||
type Service struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func New(db *gorm.DB) *Service {
|
||||
return &Service{db: db}
|
||||
}
|
Reference in New Issue
Block a user