1
0
mirror of https://github.com/garraflavatra/rolens.git synced 2025-01-18 21:17:59 +00:00
rolens/internal/app/connection.go

74 lines
1.9 KiB
Go
Raw Normal View History

2023-01-14 19:47:29 +00:00
package app
import (
2023-01-22 20:12:56 +00:00
"context"
"errors"
2023-01-14 19:47:29 +00:00
"fmt"
2023-01-22 20:12:56 +00:00
"time"
2023-01-14 19:47:29 +00:00
"github.com/wailsapp/wails/v2/pkg/runtime"
"go.mongodb.org/mongo-driver/bson"
2023-01-22 20:12:56 +00:00
"go.mongodb.org/mongo-driver/mongo"
mongoOptions "go.mongodb.org/mongo-driver/mongo/options"
2023-01-14 19:47:29 +00:00
)
2023-01-22 20:12:56 +00:00
func (a *App) connectToHost(hostKey string) (*mongo.Client, context.Context, func(), error) {
hosts, err := a.Hosts()
if err != nil {
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.InfoDialog,
Title: "Could not retrieve hosts",
})
return nil, nil, nil, errors.New("could not retrieve hosts")
}
h := hosts[hostKey]
if len(h.URI) == 0 {
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.InfoDialog,
Title: "Invalid uri",
Message: "You haven't specified a valid uri for the selected host.",
})
return nil, nil, nil, errors.New("invalid uri")
}
client, err := mongo.NewClient(mongoOptions.Client().ApplyURI(h.URI))
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Could not connect to " + h.Name,
Message: err.Error(),
})
return nil, nil, nil, errors.New("could not establish a connection with " + h.Name)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
client.Connect(ctx)
return client, ctx, func() {
client.Disconnect(ctx)
cancel()
}, nil
}
2023-01-14 19:47:29 +00:00
func (a *App) OpenConnection(hostKey string) (databases []string) {
client, ctx, close, err := a.connectToHost(hostKey)
if err != nil {
fmt.Println(err.Error())
return nil
}
databases, err = client.ListDatabaseNames(ctx, bson.M{})
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Could not retrieve database list",
Message: err.Error(),
})
return nil
}
defer close()
return databases
}