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

120 lines
2.5 KiB
Go
Raw Permalink Normal View History

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) error {
if !s.DB.HasTable(&model.User{}) {
s.DB.CreateTable(&model.User{})
}
if err := server.Handle(http.MethodGet, "/user/{id}", s.getUserByID); err != nil {
return err
}
if err := server.Handle(http.MethodGet, "/users", s.getAllUsers); err != nil {
return err
}
if err := server.Handle(http.MethodPost, "/user", s.createUser); err != nil {
return err
}
if err := server.Handle(http.MethodPut, "/user/{id}", s.updateUser); err != nil {
return err
}
if err := server.Handle(http.MethodDelete, "/user/{id}", s.deleteUser); err != nil {
return err
}
return nil
}
2020-03-29 15:24:35 +00:00
type userList struct {
Users []model.User
}
2020-03-29 15:24:35 +00:00
func (s Service) getAllUsers() (*userList, api.Error) {
users := userList{}
s.DB.Find(&users.Users)
return &users, api.ErrorSuccess
}
2020-03-29 15:24:35 +00:00
func (s Service) getUserByID(param struct{ ID uint }) (*model.User, api.Error) {
var user model.User
if s.DB.First(&user, param.ID).RecordNotFound() {
return nil, api.ErrorNoMatchFound
}
return &user, api.ErrorSuccess
}
2020-03-29 15:24:35 +00:00
type createRequest struct {
Username string
Firstname string
Lastname string
}
func (s Service) createUser(param createRequest) (*model.User, api.Error) {
user := model.User{
Username: param.Username,
Firstname: param.Firstname,
Lastname: param.Lastname,
}
s.DB.Create(&user)
if s.DB.Last(&user).RecordNotFound() {
return nil, api.ErrorNoMatchFound
}
return &user, api.ErrorSuccess
}
2020-03-29 15:24:35 +00:00
type updateRequest struct {
ID uint
Username *string
Firstname *string
Lastname *string
}
func (s Service) updateUser(param updateRequest) (*model.User, api.Error) {
var user model.User
if s.DB.First(&user, param.ID).RecordNotFound() {
return nil, api.ErrorNoMatchFound
}
// override with updated values
if param.Username != nil {
user.Username = *param.Username
}
if param.Firstname != nil {
user.Firstname = *param.Firstname
}
if param.Lastname != nil {
user.Lastname = *param.Lastname
}
// update
if s.DB.Save(&user).RowsAffected < 1 {
return nil, api.ErrorFailure
}
return &user, api.ErrorSuccess
}
2020-03-29 15:24:35 +00:00
func (s Service) deleteUser(param struct{ ID uint }) api.Error {
user := model.User{
ID: param.ID,
}
s.DB.Delete(&user)
2020-03-28 14:02:42 +00:00
return api.ErrorSuccess
}