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

100 lines
2.2 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) error {
if !s.DB.HasTable(&model.Article{}) {
s.DB.CreateTable(&model.Article{})
}
if err := server.Handle(http.MethodGet, "/articles", s.getAllArticles); err != nil {
return err
}
if err := server.Handle(http.MethodGet, "/user/{id}/articles", s.getArticlesByAuthor); err != nil {
return err
}
if err := server.Handle(http.MethodGet, "/article/{id}", s.getArticleByID); err != nil {
return err
}
if err := server.Handle(http.MethodPost, "/article", s.postArticle); err != nil {
return err
}
if err := server.Handle(http.MethodDelete, "/article/{id}", s.deleteArticle); err != nil {
return err
}
return nil
}
2020-03-29 15:24:35 +00:00
type articleInfo struct {
ID uint
Author uint
Title string
Body string
Score uint
}
2020-03-29 15:24:35 +00:00
type articleList struct {
Articles []model.Article
}
2020-03-29 15:24:35 +00:00
func (s Service) getArticlesByAuthor(param struct{ ID uint }) (*articleList, api.Error) {
articles := make([]model.Article, 0)
s.DB.Where("author = ?", param.ID).Find(&articles)
2020-03-29 15:24:35 +00:00
return &articleList{
Articles: articles,
}, api.ErrorSuccess
}
2020-03-29 15:24:35 +00:00
func (s Service) getAllArticles() (*articleList, api.Error) {
articles := make([]model.Article, 0)
s.DB.Find(&articles)
2020-03-29 15:24:35 +00:00
return &articleList{
Articles: articles,
}, api.ErrorSuccess
}
2020-03-29 15:24:35 +00:00
func (s Service) getArticleByID(param struct{ ID uint }) (*articleInfo, api.Error) {
var article model.Article
if s.DB.First(&article, param.ID).RecordNotFound() {
return nil, api.ErrorNoMatchFound
}
2020-03-29 15:24:35 +00:00
return &articleInfo{
ID: article.ID,
Title: article.Title,
Body: article.Body,
Author: article.Author,
}, api.ErrorSuccess
}
2020-03-29 15:24:35 +00:00
type createRequest struct {
Title string
Body string
}
func (s Service) postArticle(param createRequest) (*articleInfo, api.Error) {
return nil, api.ErrorNotImplemented
}
2020-03-29 15:24:35 +00:00
func (s Service) deleteArticle(param struct{ ID uint }) api.Error {
article := model.Article{
ID: param.ID,
}
s.DB.Delete(&article)
2020-03-28 14:02:42 +00:00
return api.ErrorSuccess
}