diff --git a/cmd/bot/channel.go b/cmd/bot/channel.go index ea01443..bf26888 100644 --- a/cmd/bot/channel.go +++ b/cmd/bot/channel.go @@ -34,6 +34,15 @@ func (app *Application) AddChannel(login string, message twitch.PrivateMessage) } } +func (app *Application) GetAllChannels() { + channel, err := app.Models.Channels.GetAll() + if err != nil { + app.Logger.Error(err) + } + app.Logger.Infow("All channels:", + "channel", channel) +} + func (app *Application) DeleteChannel(login string, message twitch.PrivateMessage) { err := app.Models.Channels.Delete(login) if err != nil { diff --git a/cmd/bot/main.go b/cmd/bot/main.go index aaf65ba..af3ddf9 100644 --- a/cmd/bot/main.go +++ b/cmd/bot/main.go @@ -99,6 +99,7 @@ func main() { common.StartTime() common.Send("nourylul", "xd", app.TwitchClient) + app.GetAllChannels() }) app.TwitchClient.Join("nourylul") diff --git a/internal/data/channel.go b/internal/data/channel.go index c8280fd..9354670 100644 --- a/internal/data/channel.go +++ b/internal/data/channel.go @@ -1,6 +1,7 @@ package data import ( + "context" "database/sql" "errors" "time" @@ -74,6 +75,59 @@ func (c ChannelModel) Get(login string) (*Channel, error) { return &channel, nil } +// GetAll() returns a slice of all channels in the database. +func (c ChannelModel) GetAll() ([]*Channel, error) { + query := ` + SELECT id, added_at, login, twitchid + FROM channels + ORDER BY id` + + // Create a context with 3 seconds timeout. + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + + // Use QueryContext() the context and query. This returns a + // sql.Rows resultset containing our channels. + rows, err := c.DB.QueryContext(ctx, query) + if err != nil { + return nil, err + } + + // Need to defer a call to rows.Close() to ensure the resultset + // is closed before GetAll() returns. + defer rows.Close() + + // Initialize an empty slice to hold the data. + channels := []*Channel{} + + // Iterate over the resultset. + for rows.Next() { + // Initialize an empty Channel struct where we put on + // a single channel value. + var channel Channel + + // Scan the values onto the channel struct + err := rows.Scan( + &channel.ID, + &channel.AddedAt, + &channel.Login, + &channel.TwitchID, + ) + if err != nil { + return nil, err + } + // Add the single movie struct onto the slice. + channels = append(channels, &channel) + } + + // When rows.Next() finishes call rows.Err() to retrieve any errors. + if err = rows.Err(); err != nil { + return nil, err + } + + return channels, nil +} + func (c ChannelModel) Delete(login string) error { // Prepare the statement. query := ` diff --git a/internal/data/models.go b/internal/data/models.go index d668a23..0d3f54b 100644 --- a/internal/data/models.go +++ b/internal/data/models.go @@ -17,6 +17,7 @@ type Models struct { Channels interface { Insert(channel *Channel) error Get(login string) (*Channel, error) + GetAll() ([]*Channel, error) Delete(login string) error } Users interface {