package repository import ( "context" "database/sql" "errors" "fmt" "time" "git.jamestombleson.com/jtom38/newsbot-api/internal/domain" "github.com/huandu/go-sqlbuilder" ) type AlertDiscordRepo interface { Create(ctx context.Context, userId, sourceId, webhookId int64) (int64, error) SoftDelete(ctx context.Context, id int64) (int64, error) Restore(ctx context.Context, id int64) (int64, error) Delete(ctx context.Context, id int64) (int64, error) ListByUser(ctx context.Context, page, limit int, userId int64) ([]domain.AlertDiscordEntity, error) } type alertDiscordRepository struct { conn *sql.DB defaultLimit int defaultOffset int } func NewAlertDiscordRepository(conn *sql.DB) alertDiscordRepository { return alertDiscordRepository{ conn: conn, defaultLimit: 50, defaultOffset: 50, } } func (r alertDiscordRepository) Create(ctx context.Context, userId, sourceId, webhookId int64) (int64, error) { dt := time.Now() queryBuilder := sqlbuilder.NewInsertBuilder() queryBuilder.InsertInto("AlertDiscord") queryBuilder.Cols("UpdatedAt", "CreatedAt", "DeletedAt", "UserID", "SourceID", "DiscordWebHookID") queryBuilder.Values(dt, dt, timeZero, userId, sourceId, webhookId) query, args := queryBuilder.Build() _, err := r.conn.ExecContext(ctx, query, args...) if err != nil { return 0, err } return 1, nil } func (r alertDiscordRepository) SoftDelete(ctx context.Context, id int64) (int64, error) { return softDeleteRow(ctx, r.conn, "AlertDiscord", id) } func (r alertDiscordRepository) Restore(ctx context.Context, id int64) (int64, error) { return restoreRow(ctx, r.conn, "AlertDiscord", id) } func (r alertDiscordRepository) Delete(ctx context.Context, id int64) (int64, error) { return deleteFromTable(ctx, r.conn, "AlertDiscord", id) } func (r alertDiscordRepository) ListByUser(ctx context.Context, page, limit int, userId int64) ([]domain.AlertDiscordEntity, error) { builder := sqlbuilder.NewSelectBuilder() builder.Select("*") builder.From("AlertDiscord") builder.Where( builder.Equal("UserID", userId), ) builder.Offset(page * limit) builder.Limit(limit) query, args := builder.Build() rows, err := r.conn.QueryContext(ctx, query, args...) if err != nil { return []domain.AlertDiscordEntity{}, err } data := r.processRows(rows) if len(data) == 0 { return []domain.AlertDiscordEntity{}, errors.New(ErrUserNotFound) } return data, nil } func (ur alertDiscordRepository) processRows(rows *sql.Rows) []domain.AlertDiscordEntity { items := []domain.AlertDiscordEntity{} for rows.Next() { var id int64 var createdAt time.Time var updatedAt time.Time var deletedAt time.Time var userId int64 var sourceId int64 var webhookId int64 err := rows.Scan( &id, &createdAt, &updatedAt, &deletedAt, &userId, &sourceId, &webhookId, ) if err != nil { fmt.Println(err) } item := domain.AlertDiscordEntity{ ID: id, CreatedAt: createdAt, UpdatedAt: updatedAt, DeletedAt: deletedAt, UserID: userId, SourceID: sourceId, DiscordWebHookId: webhookId, } items = append(items, item) } return items }