Skip to content
This repository has been archived by the owner on Feb 7, 2024. It is now read-only.

Commit

Permalink
feat: add document views count (#1)
Browse files Browse the repository at this point in the history
  • Loading branch information
MrMissx authored Nov 4, 2023
1 parent fc07519 commit 08baae5
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 7 deletions.
2 changes: 2 additions & 0 deletions models/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@ func Connect() {
log.Fatal("DB_URI is not set")
}

log.Println("Connecting to database...")
db, err := gorm.Open(postgres.Open(uri), &gorm.Config{TranslateError: true})
if err != nil {
panic(err)
}
log.Println("Database connected!")

log.Println("Migrating database...")
if err := db.AutoMigrate(&Document{}); err != nil {
Expand Down
16 changes: 12 additions & 4 deletions models/document.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@ import (
)

type Document struct {
Id uint `gorm:"primary_key;auto_increment" json:"id"`
Slug string `gorm:"type:varchar(10);unique;not null" json:"key"`
Content string `gorm:"type:text;not null" json:"content"`
CreatedAt *time.Time `gorm:"not null" json:"date"`
Id uint `json:"id" gorm:"primary_key;auto_increment"`
Slug string `json:"key" gorm:"type:varchar(10);unique;not null;unqiueIndex"`
Content string `json:"content" gorm:"type:text;not null"`
CreatedAt *time.Time `json:"date" gorm:"not null"`
Views uint `json:"views" gorm:"type:int;not null;default:0"`
}

func (Document) TableName() string {
Expand All @@ -37,6 +38,11 @@ func SaveDocument(document *Document) error {
return insertDocument(document, 0)
}

func incrementViews(document *Document) {
document.Views += 1
DB.Model(&document).Update("views", document.Views)
}

// Get document by slug (key) that are assigned to it
func GetDocumentBySlug(slug string) (*Document, error) {

Expand All @@ -46,5 +52,7 @@ func GetDocumentBySlug(slug string) (*Document, error) {
return nil, err
}

go incrementViews(&document)

return &document, nil
}
2 changes: 0 additions & 2 deletions stashbin.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@ func main() {
}))
r.Use(gin.Recovery())

log.Println("Connecting to database")
models.Connect()
log.Println("Connected to database")

log.Println("Registering routes")
r.GET("/api/health", controllers.HealthCheck)
Expand Down
3 changes: 2 additions & 1 deletion utils/slug.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ var letters = []rune("abcdefghijklmnopqrstuvwxyz")

func CreateSlug() string {
b := make([]rune, length)
idx := len(letters)

for i := range b {
b[i] = letters[rand.Intn(len(letters))]
b[i] = letters[rand.Intn(idx)]
}
return string(b)
}

0 comments on commit 08baae5

Please sign in to comment.