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

124 lines
3.0 KiB
Go

package user
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.User{}) {
s.DB.CreateTable(&model.User{})
}
server.Handle(http.MethodGet, "/users", s.getAllUsers)
server.Handle(http.MethodGet, "/user/{id}", s.getUserByID)
server.Handle(http.MethodPost, "/user", s.createUser)
server.Handle(http.MethodPut, "/user/{id}", s.updateUser)
server.Handle(http.MethodDelete, "/user/{id}", s.deleteUser)
}
func (s Service) getAllUsers(req api.Request, res *api.Response) api.Error {
users := make([]model.User, 0)
s.DB.Find(&users)
res.SetData("users", users)
return api.ErrorSuccess
}
func (s Service) getUserByID(req api.Request, res *api.Response) api.Error {
id, err := req.Param.GetUint("user_id")
if err != nil {
return api.ErrorInvalidParam
}
var user model.User
if s.DB.First(&user, id).RecordNotFound() {
return api.ErrorNoMatchFound
}
res.SetData("id", user.ID)
res.SetData("username", user.Username)
res.SetData("firstname", user.Firstname)
res.SetData("lastname", user.Lastname)
res.SetData("articles", user.Articles)
return api.ErrorSuccess
}
func (s Service) createUser(req api.Request, res *api.Response) api.Error {
var user model.User
var err error
user.Username, err = req.Param.GetString("username")
if err != nil {
return api.ErrorInvalidParam
}
user.Firstname, err = req.Param.GetString("firstname")
if err != nil {
return api.ErrorInvalidParam
}
user.Lastname, err = req.Param.GetString("lastname")
if err != nil {
return api.ErrorInvalidParam
}
s.DB.Create(&user)
if s.DB.Last(&user).RecordNotFound() {
return api.ErrorNoMatchFound
}
res.SetData("id", user.ID)
res.SetData("username", user.Username)
res.SetData("firstname", user.Firstname)
res.SetData("lastname", user.Lastname)
res.SetData("articles", user.Articles)
return api.ErrorSuccess
}
func (s Service) updateUser(req api.Request, res *api.Response) api.Error {
id, err := req.Param.GetUint("user_id")
if err != nil {
return api.ErrorInvalidParam
}
var user model.User
if s.DB.First(&user, id).RecordNotFound() {
return api.ErrorNoMatchFound
}
// override with updated values
if updated, err := req.Param.GetString("username"); err == nil {
user.Username = updated
}
if updated, err := req.Param.GetString("firstname"); err == nil {
user.Firstname = updated
}
if updated, err := req.Param.GetString("lastname"); err == nil {
user.Lastname = updated
}
// update
if s.DB.Save(&user).RowsAffected < 1 {
return api.ErrorFailure
}
return api.ErrorSuccess
}
func (s Service) deleteUser(req api.Request, res *api.Response) api.Error {
id, err := req.Param.GetUint("user_id")
if err != nil {
return api.ErrorInvalidParam
}
user := model.User{}
user.ID = id
s.DB.Delete(&user)
return api.ErrorSuccess
}