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