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 } type oUserList struct { Users []model.User } type oUser struct { ID uint Username string Firstname string Lastname string Articles interface{} } type iByID struct { ID uint } type iCreate struct { Username string Firstname string Lastname string } type iUpdate struct { ID uint Username *string Firstname *string Lastname *string } func (s Service) getAllUsers() (*oUserList, api.Error) { users := oUserList{} s.DB.Find(&users.Users) return &users, api.ErrorSuccess } func (s Service) getUserByID(param iByID) (*oUser, api.Error) { var user model.User if s.DB.First(&user, param.ID).RecordNotFound() { return nil, api.ErrorNoMatchFound } return &oUser{ ID: user.ID, Username: user.Username, Firstname: user.Firstname, Lastname: user.Lastname, Articles: user.Articles, }, api.ErrorSuccess } func (s Service) createUser(param iCreate) (*oUser, 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 &oUser{ ID: user.ID, Username: user.Username, Firstname: user.Firstname, Lastname: user.Lastname, Articles: user.Articles, }, api.ErrorSuccess } func (s Service) updateUser(param iUpdate) (*oUser, 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 &oUser{ ID: user.ID, Username: user.Username, Firstname: user.Firstname, Lastname: user.Lastname, Articles: user.Articles, }, api.ErrorSuccess } func (s Service) deleteUser(param iByID) api.Error { user := model.User{ ID: param.ID, } s.DB.Delete(&user) return api.ErrorSuccess }