src.dualinventive.com/go/cp3000-interface/internal/storage/databaseRepository.go

64 lines
1.6 KiB
Go

package storage
import (
"fmt"
"regexp"
"github.com/jinzhu/gorm"
// Import only the mysql driver for the connection. Functions are not needed.
_ "github.com/jinzhu/gorm/dialects/mysql"
)
// DatabaseRepository contains functions to interact with a MySQL database
type DatabaseRepository struct {
db *gorm.DB
}
// NewDatabaseRepository returns a repository that interacts with a MySQL database
func NewDatabaseRepository(host, user, password, name string) (*DatabaseRepository, error) {
var err error
constring := fmt.Sprintf("%s:%s@(%s)/%s?charset=utf8&parseTime=True&loc=Local",
user,
password,
host,
name)
dbHandle, err := gorm.Open("mysql", constring)
if err != nil {
return nil, fmt.Errorf("failed to connect database: %v", err)
}
r := &DatabaseRepository{
db: dbHandle,
}
return r, nil
}
// GetDeviceByIMEI returns a device by it's IMEI
func (c *DatabaseRepository) GetDeviceByIMEI(imei string) (*Device, error) {
v := &Device{}
if err := c.db.First(v, "imei = ?", imei).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return nil, ErrNotFound
}
return nil, err
}
return v, nil
}
// GetDeviceByDeviceUID returns a device by it's device UID
func (c *DatabaseRepository) GetDeviceByDeviceUID(deviceUID string) (*Device, error) {
var devRegex = regexp.MustCompile(`^010+([0-9]+)$`)
res := devRegex.FindStringSubmatch(deviceUID)
if len(res) < 2 {
return nil, ErrNotFound
}
v := &Device{}
if err := c.db.First(v, "id = ?", res[1]).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return nil, ErrNotFound
}
return nil, err
}
return v, nil
}