tiny-url-ex/service/article/article.go

86 lines
2.1 KiB
Go
Raw Normal View History

package article
import (
"net/http"
"git.xdrm.io/go/aicra"
"git.xdrm.io/go/aicra/api"
"git.xdrm.io/go/tiny-url-ex/service/model"
"github.com/jinzhu/gorm"
)
// Service to manage users
type Service struct {
DB *gorm.DB
}
// Wire services to their paths
func (s Service) Wire(server *aicra.Server) {
if !s.DB.HasTable(&model.Article{}) {
s.DB.CreateTable(&model.Article{})
}
server.HandleFunc(http.MethodGet, "/articles", s.getAllArticles)
server.HandleFunc(http.MethodGet, "/user/{id}/articles", s.getArticlesByAuthor)
server.HandleFunc(http.MethodGet, "/article/{id}", s.getArticleByID)
server.HandleFunc(http.MethodPost, "/article", s.postArticle)
server.HandleFunc(http.MethodDelete, "/article/{id}", s.deleteArticle)
}
func (s Service) getArticlesByAuthor(req api.Request, res *api.Response) {
id, err := req.Param.GetUint("author_id")
if err != nil {
res.SetError(api.ErrorInvalidParam(), "author_id")
return
}
articles := make([]model.Article, 0)
s.DB.Where("author = ?", id).Find(&articles)
res.SetData("articles", articles)
res.SetError(api.ErrorSuccess())
}
func (s Service) getAllArticles(req api.Request, res *api.Response) {
articles := make([]model.Article, 0)
s.DB.Find(&articles)
res.SetData("articles", articles)
res.SetError(api.ErrorSuccess())
}
func (s Service) getArticleByID(req api.Request, res *api.Response) {
id, err := req.Param.GetUint("article_id")
if err != nil {
res.SetError(api.ErrorInvalidParam(), "article_id")
return
}
var article model.Article
if s.DB.First(&article, id).RecordNotFound() {
res.SetError(api.ErrorNoMatchFound())
return
}
res.SetData("id", article.ID)
res.SetData("title", article.Title)
res.SetData("body", article.Body)
res.SetData("author", article.Author)
res.SetError(api.ErrorSuccess())
}
func (s Service) postArticle(req api.Request, res *api.Response) {
}
func (s Service) deleteArticle(req api.Request, res *api.Response) {
id, err := req.Param.GetUint("user_id")
if err != nil {
res.SetError(api.ErrorInvalidParam(), "user_id")
return
}
article := model.Article{}
article.ID = id
s.DB.Delete(&article)
res.SetError(api.ErrorSuccess())
}