103 lines
2.1 KiB
Go
103 lines
2.1 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 iByID struct {
|
|
ID uint
|
|
}
|
|
|
|
type oArticle struct {
|
|
ID uint
|
|
Author uint
|
|
Title string
|
|
Body string
|
|
Score uint
|
|
}
|
|
type iCreate struct {
|
|
Title string
|
|
Body string
|
|
}
|
|
|
|
type oArticleList struct {
|
|
Articles []model.Article
|
|
}
|
|
|
|
func (s Service) getArticlesByAuthor(param iByID) (*oArticleList, api.Error) {
|
|
articles := make([]model.Article, 0)
|
|
s.DB.Where("author = ?", param.ID).Find(&articles)
|
|
return &oArticleList{
|
|
Articles: articles,
|
|
}, api.ErrorSuccess
|
|
}
|
|
|
|
func (s Service) getAllArticles() (*oArticleList, api.Error) {
|
|
articles := make([]model.Article, 0)
|
|
s.DB.Find(&articles)
|
|
return &oArticleList{
|
|
Articles: articles,
|
|
}, api.ErrorSuccess
|
|
}
|
|
|
|
func (s Service) getArticleByID(param iByID) (*oArticle, api.Error) {
|
|
var article model.Article
|
|
if s.DB.First(&article, param.ID).RecordNotFound() {
|
|
return nil, api.ErrorNoMatchFound
|
|
}
|
|
|
|
return &oArticle{
|
|
ID: article.ID,
|
|
Title: article.Title,
|
|
Body: article.Body,
|
|
Author: article.Author,
|
|
}, api.ErrorSuccess
|
|
}
|
|
|
|
func (s Service) postArticle(param iCreate) (*oArticle, api.Error) {
|
|
return nil, api.ErrorNotImplemented
|
|
}
|
|
|
|
func (s Service) deleteArticle(param iByID) api.Error {
|
|
article := model.Article{
|
|
ID: param.ID,
|
|
}
|
|
s.DB.Delete(&article)
|
|
|
|
return api.ErrorSuccess
|
|
}
|