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.Handle(http.MethodGet, "/articles", s.getAllArticles) server.Handle(http.MethodGet, "/user/{id}/articles", s.getArticlesByAuthor) server.Handle(http.MethodGet, "/article/{id}", s.getArticleByID) server.Handle(http.MethodPost, "/article", s.postArticle) server.Handle(http.MethodDelete, "/article/{id}", s.deleteArticle) } func (s Service) getArticlesByAuthor(req api.Request, res *api.Response) api.Error { id, err := req.Param.GetUint("author_id") if err != nil { return api.ErrorInvalidParam } articles := make([]model.Article, 0) s.DB.Where("author = ?", id).Find(&articles) res.SetData("articles", articles) return api.ErrorSuccess } func (s Service) getAllArticles(req api.Request, res *api.Response) api.Error { articles := make([]model.Article, 0) s.DB.Find(&articles) res.SetData("articles", articles) return api.ErrorSuccess } func (s Service) getArticleByID(req api.Request, res *api.Response) api.Error { id, err := req.Param.GetUint("article_id") if err != nil { return api.ErrorInvalidParam } var article model.Article if s.DB.First(&article, id).RecordNotFound() { return api.ErrorNoMatchFound } res.SetData("id", article.ID) res.SetData("title", article.Title) res.SetData("body", article.Body) res.SetData("author", article.Author) return api.ErrorSuccess } func (s Service) postArticle(req api.Request, res *api.Response) api.Error { return api.ErrorNotImplemented } func (s Service) deleteArticle(req api.Request, res *api.Response) api.Error { id, err := req.Param.GetUint("user_id") if err != nil { return api.ErrorInvalidParam } article := model.Article{} article.ID = id s.DB.Delete(&article) return api.ErrorSuccess }