2017-01-25 16:11:35 +00:00
|
|
|
package datastore
|
|
|
|
|
|
|
|
import (
|
2018-04-25 11:45:21 +00:00
|
|
|
"database/sql"
|
2018-04-24 08:28:23 +00:00
|
|
|
"github.com/usefathom/fathom/pkg/models"
|
2017-01-25 16:11:35 +00:00
|
|
|
)
|
|
|
|
|
2017-01-25 19:01:02 +00:00
|
|
|
// GetUser retrieves user from datastore by its ID
|
2018-04-25 11:45:21 +00:00
|
|
|
func GetUser(ID int64) (*models.User, error) {
|
|
|
|
u := &models.User{}
|
2018-04-25 12:29:32 +00:00
|
|
|
query := dbx.Rebind("SELECT * FROM users WHERE id = ? LIMIT 1")
|
|
|
|
err := dbx.Get(u, query, ID)
|
2018-04-25 11:45:21 +00:00
|
|
|
|
2017-01-25 21:48:24 +00:00
|
|
|
if err != nil {
|
2018-04-25 11:45:21 +00:00
|
|
|
if err == sql.ErrNoRows {
|
|
|
|
return nil, ErrNoResults
|
|
|
|
}
|
|
|
|
|
2017-01-25 21:48:24 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2018-04-25 11:45:21 +00:00
|
|
|
return u, err
|
2017-01-25 16:11:35 +00:00
|
|
|
}
|
|
|
|
|
2017-01-25 19:01:02 +00:00
|
|
|
// GetUserByEmail retrieves user from datastore by its email
|
2017-01-25 16:11:35 +00:00
|
|
|
func GetUserByEmail(email string) (*models.User, error) {
|
2018-04-25 11:45:21 +00:00
|
|
|
u := &models.User{}
|
2018-04-25 12:29:32 +00:00
|
|
|
query := dbx.Rebind("SELECT * FROM users WHERE email = ? LIMIT 1")
|
|
|
|
err := dbx.Get(u, query, email)
|
2017-01-25 21:48:24 +00:00
|
|
|
if err != nil {
|
2018-04-25 11:45:21 +00:00
|
|
|
if err == sql.ErrNoRows {
|
|
|
|
return nil, ErrNoResults
|
|
|
|
}
|
|
|
|
|
2017-01-25 21:48:24 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2018-04-25 11:45:21 +00:00
|
|
|
return u, err
|
2017-01-25 16:11:35 +00:00
|
|
|
}
|
2018-04-25 11:25:34 +00:00
|
|
|
|
|
|
|
// SaveUser inserts the user model in the connected database
|
|
|
|
func SaveUser(u *models.User) error {
|
2018-04-25 12:29:32 +00:00
|
|
|
var query = dbx.Rebind("INSERT INTO users(email, password) VALUES(?, ?)")
|
|
|
|
result, err := dbx.Exec(query, u.Email, u.Password)
|
2018-04-25 11:25:34 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
u.ID, _ = result.LastInsertId()
|
|
|
|
return nil
|
|
|
|
}
|