82 lines
1.8 KiB
Go
82 lines
1.8 KiB
Go
package gormstore
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"fmt"
|
|
"git.itzana.me/StrafesNET/dev-service/pkg/datastore"
|
|
"git.itzana.me/StrafesNET/dev-service/pkg/model"
|
|
"git.itzana.me/strafesnet/utils/logger"
|
|
log "github.com/sirupsen/logrus"
|
|
"github.com/urfave/cli/v2"
|
|
"gorm.io/driver/postgres"
|
|
"gorm.io/gorm"
|
|
"strconv"
|
|
)
|
|
|
|
type Gormstore struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func New(ctx *cli.Context) (datastore.Datastore, error) {
|
|
db, err := gorm.Open(
|
|
postgres.Open(
|
|
fmt.Sprintf(
|
|
"host=%s user=%s password=%s dbname=%s port=%d",
|
|
ctx.String("pg-host"),
|
|
ctx.String("pg-user"),
|
|
ctx.String("pg-password"),
|
|
ctx.String("pg-db"),
|
|
ctx.Int("pg-port")),
|
|
), &gorm.Config{
|
|
Logger: logger.New(),
|
|
})
|
|
if err != nil {
|
|
log.WithError(err).Errorln("failed to connect to database")
|
|
return nil, err
|
|
}
|
|
|
|
if ctx.Bool("migrate") {
|
|
if err := db.AutoMigrate(
|
|
&model.Application{},
|
|
&model.Request{},
|
|
&model.Permission{},
|
|
&model.UserRole{},
|
|
&model.RateLimit{},
|
|
&model.User{},
|
|
); err != nil {
|
|
log.WithError(err).Errorln("database migration failed")
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
store := &Gormstore{db}
|
|
|
|
// Automatically ensure default data exists
|
|
if err := store.EnsureDefaultData(ctx.Context); err != nil {
|
|
log.WithError(err).Warnln("failed to ensure default data")
|
|
return nil, err
|
|
}
|
|
|
|
return store, nil
|
|
|
|
}
|
|
|
|
// Helper functions for cursor encoding/decoding
|
|
func encodeCursor(id uint64) string {
|
|
// Convert ID to base64-encoded string
|
|
return base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%d", id)))
|
|
}
|
|
|
|
func decodeCursor(cursor string) (uint64, error) {
|
|
// Decode the cursor from base64 back to an ID
|
|
decoded, err := base64.StdEncoding.DecodeString(cursor)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
id, err := strconv.ParseUint(string(decoded), 10, 64)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return id, nil
|
|
}
|