I'm trying to check if an user already have a email. I wrote a function like this :
func IsUniqueEmail(body io.ReadCloser) (database.User, error) {
connection := database.GetDatabase()
defer database.CloseDatabase(connection)
var user database.User
err := json.NewDecoder(body).Decode(&user)
if err != nil {
return user, err
}
var dbuser database.User
connection.Where("email = ?", user.Email).First(&dbuser)
fmt.Println("User: ", dbuser)
fmt.Println("User: ", dbuser.Email)
return dbuser, nil}
but the fmt.Println show me
User: {{0 0001-01-01 00:00:00 0000 UTC 0001-01-01 00:00:00 0000 UTC } }
I assume where is no email in dbuser but I can't understand why anyone have an idea ? Cheers
CodePudding user response:
If you are using gorm v2, you can catch the record not found error
var dbuser database.User
err := connection.Where("email = ?", user.Email).First(&dbuser).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return dbuser, err
}
fmt.Println("User: ", dbuser)
fmt.Println("User: ", dbuser.Email)
return dbuser, nil}
CodePudding user response:
The solution
func IsUniqueEmail(body io.ReadCloser) (database.User, bool, error) {
var dbuser database.User
connection := database.GetDatabase()
defer database.CloseDatabase(connection)
var user database.User
err := json.NewDecoder(body).Decode(&user)
if err != nil {
return user, false, err
}
errDB := connection.Where("email = ?", user.Email).First(&dbuser).Error
if errors.Is(errDB, gorm.ErrRecordNotFound) {
return dbuser, true, errDB
}
if dbuser.Email != "" {
return dbuser, false, nil
}
return user, true, nil
}