52 lines
966 B
Go
52 lines
966 B
Go
|
package store
|
||
|
|
||
|
import (
|
||
|
"crypto/rand"
|
||
|
"time"
|
||
|
|
||
|
"github.com/oklog/ulid/v2"
|
||
|
"github.com/rs/zerolog/log"
|
||
|
"gorm.io/gorm"
|
||
|
)
|
||
|
|
||
|
type Site struct {
|
||
|
ID string `gorm:"primaryKey"`
|
||
|
Domain string `gorm:"unique"`
|
||
|
URL string
|
||
|
CreatedAt *time.Time
|
||
|
FirstSeen *time.Time
|
||
|
LastSeen *time.Time
|
||
|
Tags []SiteTag `gorm:"foreignKey:SiteID"`
|
||
|
db *gorm.DB `gorm:"-"`
|
||
|
}
|
||
|
|
||
|
func (Site) TableName() string {
|
||
|
return "sites"
|
||
|
}
|
||
|
|
||
|
func (s *Store) AddSite(url string) (*Site, error) {
|
||
|
ID := ulid.MustNew(ulid.Timestamp(time.Now()), rand.Reader).String()
|
||
|
createdAt := time.Now()
|
||
|
site := &Site{
|
||
|
ID: ID,
|
||
|
URL: url,
|
||
|
CreatedAt: &createdAt,
|
||
|
db: s.db,
|
||
|
}
|
||
|
|
||
|
result := s.db.Create(site)
|
||
|
if result.Error != nil {
|
||
|
log.Error().
|
||
|
Str("siteid", ID).
|
||
|
Err(result.Error).
|
||
|
Msg("unable to insert site into db")
|
||
|
return nil, result.Error
|
||
|
}
|
||
|
|
||
|
log.Debug().
|
||
|
Str("siteid", ID).
|
||
|
Str("url", url).
|
||
|
Msg("site added to db")
|
||
|
return site, nil
|
||
|
}
|