100 lines
2.2 KiB
Go
100 lines
2.2 KiB
Go
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
|
|
}
|
|
|
|
type articleInfo struct {
|
|
ID uint
|
|
Author uint
|
|
Title string
|
|
Body string
|
|
Score uint
|
|
}
|
|
|
|
type articleList struct {
|
|
Articles []model.Article
|
|
}
|
|
|
|
func (s Service) getArticlesByAuthor(param struct{ ID uint }) (*articleList, api.Error) {
|
|
articles := make([]model.Article, 0)
|
|
s.DB.Where("author = ?", param.ID).Find(&articles)
|
|
return &articleList{
|
|
Articles: articles,
|
|
}, api.ErrorSuccess
|
|
}
|
|
|
|
func (s Service) getAllArticles() (*articleList, api.Error) {
|
|
articles := make([]model.Article, 0)
|
|
s.DB.Find(&articles)
|
|
return &articleList{
|
|
Articles: articles,
|
|
}, api.ErrorSuccess
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
return &articleInfo{
|
|
ID: article.ID,
|
|
Title: article.Title,
|
|
Body: article.Body,
|
|
Author: article.Author,
|
|
}, api.ErrorSuccess
|
|
}
|
|
|
|
type createRequest struct {
|
|
Title string
|
|
Body string
|
|
}
|
|
|
|
func (s Service) postArticle(param createRequest) (*articleInfo, api.Error) {
|
|
return nil, api.ErrorNotImplemented
|
|
}
|
|
|
|
func (s Service) deleteArticle(param struct{ ID uint }) api.Error {
|
|
article := model.Article{
|
|
ID: param.ID,
|
|
}
|
|
s.DB.Delete(&article)
|
|
|
|
return api.ErrorSuccess
|
|
}
|