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

Commit

Permalink
refactor(database): reorgenized packages and prepared structure for s…
Browse files Browse the repository at this point in the history
…qlite implementation
  • Loading branch information
Wittano committed Jul 28, 2024
1 parent 7e6d4ef commit aa55694
Show file tree
Hide file tree
Showing 17 changed files with 177 additions and 164 deletions.
18 changes: 9 additions & 9 deletions bot/bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import (
"github.com/wittano/komputer/bot/joke"
"github.com/wittano/komputer/bot/log"
"github.com/wittano/komputer/bot/voice"
"github.com/wittano/komputer/db"
dbJoke "github.com/wittano/komputer/db/joke"
"github.com/wittano/komputer/internal"
"github.com/wittano/komputer/internal/mongodb"
"log/slog"
"time"
)
Expand All @@ -35,7 +35,7 @@ func (sc slashCommandHandler) handleSlashCommand(s *discordgo.Session, i *discor
requestID := uuid.New().String()
loggerCtx := log.NewContext(requestID)
deadlineCtx, cancel := context.WithTimeout(loggerCtx, cmdTimeout)
ctx := context.WithValue(deadlineCtx, dbJoke.GuildIDKey, i.GuildID)
ctx := context.WithValue(deadlineCtx, mongodb.GuildIDKey, i.GuildID)
defer cancel()

userID := i.Member.User.ID
Expand Down Expand Up @@ -102,7 +102,7 @@ func handleEventResponse(ctx context.Context, s *discordgo.Session, i *discordgo
type DiscordBot struct {
ctx context.Context
bot *discordgo.Session
mongodb db.MongodbService
mongodb *mongodb.Database
spockVoiceChs voice.SpockVoiceChannels
}

Expand All @@ -124,8 +124,8 @@ func (d *DiscordBot) Close() (err error) {
return
}

func createJokeGetServices(globalCtx context.Context, database *db.MongodbDatabase) []dbJoke.SearchService {
return []dbJoke.SearchService{
func createJokeGetServices(globalCtx context.Context, database *mongodb.Database) []internal.SearchService {
return []internal.SearchService{
jokeDevServiceID: joke.NewJokeDevService(globalCtx),
humorAPIServiceID: joke.NewHumorAPIService(globalCtx),
databaseServiceID: joke.NewJokeDatabase(database),
Expand All @@ -134,7 +134,7 @@ func createJokeGetServices(globalCtx context.Context, database *db.MongodbDataba

func createCommands(
globalCtx context.Context,
services []dbJoke.SearchService,
services []internal.SearchService,
spockVoice map[string]chan struct{},
guildVoiceChats map[string]voice.ChatInfo,
) map[string]command.DiscordSlashCommandHandler {
Expand All @@ -158,7 +158,7 @@ func createCommands(
}

func createOptions(
services []dbJoke.SearchService,
services []internal.SearchService,
commands map[string]command.DiscordSlashCommandHandler,
) []command.DiscordEventHandler {
apologies := command.ApologiesOption{}
Expand Down Expand Up @@ -197,7 +197,7 @@ func NewDiscordBot(ctx context.Context) (*DiscordBot, error) {
bot.AddHandler(vcHandler.HandleVoiceChannelUpdate)

// Register slash commands
database := db.Mongodb(ctx)
database := mongodb.NewMongodb(ctx)
services := createJokeGetServices(ctx, database)
commands := createCommands(ctx, services, spockVoiceChns, guildVoiceChats)
for _, c := range commands {
Expand Down
25 changes: 13 additions & 12 deletions bot/command/joke.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import (
"fmt"
"github.com/bwmarrin/discordgo"
"github.com/wittano/komputer/bot/log"
"github.com/wittano/komputer/db/joke"
"github.com/wittano/komputer/internal"
"github.com/wittano/komputer/internal/joke"
"go.mongodb.org/mongo-driver/bson/primitive"
"log/slog"
"math/rand"
Expand All @@ -31,7 +32,7 @@ const (
)

type JokeCommand struct {
Services []joke.SearchService
Services []internal.SearchService
}

func (j JokeCommand) Command() *discordgo.ApplicationCommand {
Expand Down Expand Up @@ -82,11 +83,11 @@ findJoke:
}, nil
}

func findService(ctx context.Context, services []joke.SearchService) (joke.SearchService, error) {
func findService(ctx context.Context, services []internal.SearchService) (internal.SearchService, error) {
if len(services) == 1 {
service := services[0]

if checker, ok := service.(joke.ActiveChecker); ok && !checker.Active(ctx) {
if checker, ok := service.(internal.ActiveChecker); ok && !checker.Active(ctx) {
return nil, errors.New("all joke services is disabled")
}

Expand All @@ -100,16 +101,16 @@ func findService(ctx context.Context, services []joke.SearchService) (joke.Searc
return findService(ctx, services)
}

if activeService, ok := service.(joke.ActiveChecker); ok && !activeService.Active(ctx) {
if activeService, ok := service.(internal.ActiveChecker); ok && !activeService.Active(ctx) {
services = slices.Delete(services, i, i+1)
return findService(ctx, services)
}

return service, nil
}

// Get joke.SearchParams from Discord options
func searchParams(ctx context.Context, data discordgo.ApplicationCommandInteractionData) (query joke.SearchParams) {
// Get internal.SearchParams from Discord options
func searchParams(ctx context.Context, data discordgo.ApplicationCommandInteractionData) (query internal.SearchParams) {
query.Type, query.Category = joke.Single, joke.Any

for _, o := range data.Options {
Expand Down Expand Up @@ -179,7 +180,7 @@ func jokeTypeOption(required bool) *discordgo.ApplicationCommandOption {

type discordJoke struct {
username string
joke joke.Joke
joke joke.DbModel
}

func (j discordJoke) Response() (msg *discordgo.InteractionResponseData) {
Expand Down Expand Up @@ -303,7 +304,7 @@ func (a ApologiesOption) Execute(_ context.Context, _ *discordgo.Session, _ *dis
}

type NextJokeOption struct {
Services []joke.SearchService
Services []internal.SearchService
}

func (n NextJokeOption) Match(customID string) bool {
Expand All @@ -316,7 +317,7 @@ func (n NextJokeOption) Execute(ctx context.Context, _ *discordgo.Session, i *di
return nil, err
}

res, err := service.RandomJoke(ctx, joke.SearchParams{Type: randJokeType()})
res, err := service.RandomJoke(ctx, internal.SearchParams{Type: randJokeType()})
if err != nil {
return nil, err
}
Expand All @@ -334,7 +335,7 @@ func randJokeType() joke.Type {
}

type SameJokeCategoryOption struct {
Services []joke.SearchService
Services []internal.SearchService
}

func (s SameJokeCategoryOption) Match(customID string) bool {
Expand All @@ -350,7 +351,7 @@ func (s SameJokeCategoryOption) Execute(ctx context.Context, _ *discordgo.Sessio
return nil, err
}

res, err := service.RandomJoke(ctx, joke.SearchParams{Type: randJokeType(), Category: category})
res, err := service.RandomJoke(ctx, internal.SearchParams{Type: randJokeType(), Category: category})
if err != nil {
return nil, err
}
Expand Down
8 changes: 4 additions & 4 deletions bot/command/joke_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"context"
"errors"
"github.com/wittano/komputer/bot/joke"
dbJoke "github.com/wittano/komputer/db/joke"
"github.com/wittano/komputer/internal"
"go.mongodb.org/mongo-driver/mongo"
"testing"
)
Expand All @@ -21,7 +21,7 @@ func (d dumpMongoService) Client(_ context.Context) (*mongo.Client, error) {

func TestSelectGetService(t *testing.T) {
ctx := context.Background()
testServices := []dbJoke.SearchService{
testServices := []internal.SearchService{
joke.NewJokeDevService(ctx),
joke.NewHumorAPIService(ctx),
joke.NewJokeDatabase(dumpMongoService{}),
Expand All @@ -44,7 +44,7 @@ func TestSelectGetService(t *testing.T) {
func TestFindJokeService_ContextCancelled(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
testServices := []dbJoke.SearchService{
testServices := []internal.SearchService{
joke.NewJokeDevService(ctx),
joke.NewHumorAPIService(ctx),
joke.NewJokeDatabase(dumpMongoService{}),
Expand All @@ -57,7 +57,7 @@ func TestFindJokeService_ContextCancelled(t *testing.T) {

func TestFindJokeService_ServicesIsDeactivated(t *testing.T) {
ctx := context.Background()
services := []dbJoke.SearchService{
services := []internal.SearchService{
joke.NewJokeDatabase(dumpMongoService{}),
}

Expand Down
27 changes: 14 additions & 13 deletions bot/joke/humorapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import (
"errors"
"fmt"
"github.com/wittano/komputer/bot/log"
"github.com/wittano/komputer/db/joke"
"github.com/wittano/komputer/internal"
"github.com/wittano/komputer/internal/joke"
"io"
"log/slog"
"net/http"
Expand Down Expand Up @@ -46,33 +47,33 @@ func (h *HumorAPIService) Active(ctx context.Context) (active bool) {
return
}

func (h *HumorAPIService) RandomJoke(ctx context.Context, search joke.SearchParams) (joke.Joke, error) {
func (h *HumorAPIService) RandomJoke(ctx context.Context, search internal.SearchParams) (joke.DbModel, error) {
select {
case <-ctx.Done():
return joke.Joke{}, context.Canceled
return joke.DbModel{}, context.Canceled
default:
}

if !h.Active(ctx) {
return joke.Joke{}, HumorAPILimitExceededErr
return joke.DbModel{}, HumorAPILimitExceededErr
}

apiKey, ok := os.LookupEnv(humorAPIKey)
if !ok {
return joke.Joke{}, errors.New("humorAPI: missing " + humorAPIKey)
return joke.DbModel{}, errors.New("humorAPI: missing " + humorAPIKey)
}

req, err := http.NewRequestWithContext(ctx, http.MethodGet, humorApiURL+humorAPICategory(search.Category), nil)
if err != nil {
return joke.Joke{}, err
return joke.DbModel{}, err
}

req.Header["X-RapidAPI-Key"] = []string{apiKey}
req.Header["X-RapidAPI-Host"] = []string{"humor-jokes-and-memes.p.rapidapi.com"}

res, err := h.client.Do(req)
if err != nil {
return joke.Joke{}, err
return joke.DbModel{}, err
}
defer res.Body.Close()

Expand All @@ -86,7 +87,7 @@ func (h *HumorAPIService) RandomJoke(ctx context.Context, search joke.SearchPara
go unlockService(h.globalCtx, &h.m, &h.active, resetTime)
h.m.Unlock()

return joke.Joke{}, HumorAPILimitExceededErr
return joke.DbModel{}, HumorAPILimitExceededErr
} else if res.StatusCode != http.StatusOK {
msg, err := io.ReadAll(res.Body)
if err != nil {
Expand All @@ -96,26 +97,26 @@ func (h *HumorAPIService) RandomJoke(ctx context.Context, search joke.SearchPara
msg = []byte{}
}

return joke.Joke{}, fmt.Errorf("humorAPI: failed to get joke. status '%d', msg: '%s'", res.StatusCode, msg)
return joke.DbModel{}, fmt.Errorf("humorAPI: failed to get joke. status '%d', msg: '%s'", res.StatusCode, msg)
}

select {
case <-ctx.Done():
return joke.Joke{}, context.Canceled
return joke.DbModel{}, context.Canceled
default:
}

resBody, err := io.ReadAll(res.Body)
if err != nil {
return joke.Joke{}, err
return joke.DbModel{}, err
}

var humorRes humorAPIResponse
if err = json.Unmarshal(resBody, &humorRes); err != nil {
return joke.Joke{}, err
return joke.DbModel{}, err
}

return joke.Joke{
return joke.DbModel{
Category: search.Category,
Type: joke.Single,
Answer: humorRes.Content,
Expand Down
17 changes: 9 additions & 8 deletions bot/joke/humorapi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,20 @@ import (
"encoding/json"
"errors"
"github.com/jarcoal/httpmock"
"github.com/wittano/komputer/db/joke"
"github.com/wittano/komputer/internal"
"github.com/wittano/komputer/internal/joke"
"net/http"
"os"
"strconv"
"testing"
)

var (
testParams = joke.SearchParams{
testParams = internal.SearchParams{
Type: joke.Single,
Category: joke.Any,
}
testJoke = joke.Joke{
testJoke = joke.DbModel{
Question: "testQuestion",
Answer: "testAnswer",
Type: joke.Single,
Expand Down Expand Up @@ -51,17 +52,17 @@ func TestHumorAPIService_Get(t *testing.T) {
ctx := context.Background()
service := NewHumorAPIService(ctx)

joke, err := service.RandomJoke(ctx, testParams)
j, err := service.RandomJoke(ctx, testParams)
if err != nil {
t.Fatal(err)
}

if joke.Answer != testHumorAPIResponse.Content {
t.Fatalf("Invalid joke response. Expected: '%s', Result: '%s'", testHumorAPIResponse.Content, joke.Answer)
if j.Answer != testHumorAPIResponse.Content {
t.Fatalf("Invalid j response. Expected: '%s', Result: '%s'", testHumorAPIResponse.Content, j.Answer)
}

if joke.Category != testParams.Category {
t.Fatalf("Invalid category. Expected: '%s', Result: '%s'", testParams, joke.Category)
if j.Category != testParams.Category {
t.Fatalf("Invalid category. Expected: '%s', Result: '%s'", testParams, j.Category)
}
}

Expand Down
Loading

0 comments on commit aa55694

Please sign in to comment.