1
0
mirror of https://github.com/garraflavatra/rolens.git synced 2025-01-18 13:07:58 +00:00

Split a bit of backend code

This commit is contained in:
Romein van Buren 2023-01-14 20:47:29 +01:00
parent b7365b739c
commit 9662d46957
Signed by: romein
GPG Key ID: 0EFF8478ADDF6C49
15 changed files with 408 additions and 359 deletions

View File

@ -1,6 +1,6 @@
<script>
import { onMount } from 'svelte';
import { DropDatabase, Hosts, OpenCollection, OpenConnection, OpenDatabase } from '../wailsjs/go/main/App';
import { DropDatabase, Hosts, OpenCollection, OpenConnection, OpenDatabase } from '../wailsjs/go/app/App';
import AddressBar from './organisms/addressbar/index.svelte';
import Grid from './components/grid.svelte';
import CollectionDetail from './organisms/collection-detail/index.svelte';

View File

@ -1,5 +1,5 @@
<script>
import { PerformFind } from '../../../wailsjs/go/main/App';
import { PerformFind } from '../../../wailsjs/go/app/App';
import CodeExample from '../../components/code-example.svelte';
import { onMount } from 'svelte';
import { input } from '../../actions';

View File

@ -1,7 +1,7 @@
<script>
import { input } from '../../actions';
import { createEventDispatcher } from 'svelte';
import { PerformInsert } from '../../../wailsjs/go/main/App';
import { PerformInsert } from '../../../wailsjs/go/app/App';
export let collection;

View File

@ -1,12 +1,12 @@
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
// This file is automatically generated. DO NOT EDIT
import {map[string]main} from '../models';
import {map[string]app} from '../models';
import {primitive} from '../models';
import {main} from '../models';
import {app} from '../models';
export function DropDatabase(arg1:string,arg2:string):Promise<boolean>;
export function Hosts():Promise<map[string]main.Host>;
export function Hosts():Promise<map[string]app.Host>;
export function OpenCollection(arg1:string,arg2:string,arg3:string):Promise<primitive.M>;
@ -14,6 +14,6 @@ export function OpenConnection(arg1:string):Promise<Array<string>>;
export function OpenDatabase(arg1:string,arg2:string):Promise<Array<string>>;
export function PerformFind(arg1:string,arg2:string,arg3:string,arg4:string):Promise<main.findResult>;
export function PerformFind(arg1:string,arg2:string,arg3:string,arg4:string):Promise<app.findResult>;
export function PerformInsert(arg1:string,arg2:string,arg3:string,arg4:string):Promise<any>;

31
frontend/wailsjs/go/app/App.js Executable file
View File

@ -0,0 +1,31 @@
// @ts-check
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
// This file is automatically generated. DO NOT EDIT
export function DropDatabase(arg1, arg2) {
return window['go']['app']['App']['DropDatabase'](arg1, arg2);
}
export function Hosts() {
return window['go']['app']['App']['Hosts']();
}
export function OpenCollection(arg1, arg2, arg3) {
return window['go']['app']['App']['OpenCollection'](arg1, arg2, arg3);
}
export function OpenConnection(arg1) {
return window['go']['app']['App']['OpenConnection'](arg1);
}
export function OpenDatabase(arg1, arg2) {
return window['go']['app']['App']['OpenDatabase'](arg1, arg2);
}
export function PerformFind(arg1, arg2, arg3, arg4) {
return window['go']['app']['App']['PerformFind'](arg1, arg2, arg3, arg4);
}
export function PerformInsert(arg1, arg2, arg3, arg4) {
return window['go']['app']['App']['PerformInsert'](arg1, arg2, arg3, arg4);
}

View File

@ -1,31 +0,0 @@
// @ts-check
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
// This file is automatically generated. DO NOT EDIT
export function DropDatabase(arg1, arg2) {
return window['go']['main']['App']['DropDatabase'](arg1, arg2);
}
export function Hosts() {
return window['go']['main']['App']['Hosts']();
}
export function OpenCollection(arg1, arg2, arg3) {
return window['go']['main']['App']['OpenCollection'](arg1, arg2, arg3);
}
export function OpenConnection(arg1) {
return window['go']['main']['App']['OpenConnection'](arg1);
}
export function OpenDatabase(arg1, arg2) {
return window['go']['main']['App']['OpenDatabase'](arg1, arg2);
}
export function PerformFind(arg1, arg2, arg3, arg4) {
return window['go']['main']['App']['PerformFind'](arg1, arg2, arg3, arg4);
}
export function PerformInsert(arg1, arg2, arg3, arg4) {
return window['go']['main']['App']['PerformInsert'](arg1, arg2, arg3, arg4);
}

View File

@ -1,4 +1,4 @@
export namespace main {
export namespace app {
export class findResult {
total: number;

15
internal/app/app.go Normal file
View File

@ -0,0 +1,15 @@
package app
import "context"
type App struct {
ctx context.Context
}
func NewApp() *App {
return &App{}
}
func (a *App) Startup(ctx context.Context) {
a.ctx = ctx
}

View File

@ -0,0 +1,29 @@
package app
import (
"fmt"
"github.com/wailsapp/wails/v2/pkg/runtime"
"go.mongodb.org/mongo-driver/bson"
)
func (a *App) OpenCollection(hostKey, dbKey, collKey string) (result bson.M) {
client, ctx, close, err := a.connectToHost(hostKey)
if err != nil {
fmt.Println(err.Error())
return nil
}
command := bson.M{"collStats": collKey}
err = client.Database(dbKey).RunCommand(ctx, command).Decode(&result)
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Could not retrieve collection list for " + dbKey,
Message: err.Error(),
})
return nil
}
defer close()
return result
}

View File

@ -0,0 +1,129 @@
package app
import (
"encoding/json"
"fmt"
"github.com/wailsapp/wails/v2/pkg/runtime"
"go.mongodb.org/mongo-driver/bson"
mongoOptions "go.mongodb.org/mongo-driver/mongo/options"
)
type findResult struct {
Total int64 `json:"total"`
Results interface{} `json:"results"`
}
func (a *App) PerformFind(hostKey, dbKey, collKey string, formJson string) findResult {
var out findResult
var form struct {
Fields string `json:"fields"`
Limit int64 `json:"limit"`
Query string `json:"query"`
Skip int64 `json:"skip"`
Sort string `json:"sort"`
}
err := json.Unmarshal([]byte(formJson), &form)
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Couldn't parse form",
Message: err.Error(),
})
return out
}
client, ctx, close, err := a.connectToHost(hostKey)
if err != nil {
fmt.Println(err.Error())
return out
}
defer close()
var query bson.M
var projection bson.M
var sort bson.M
err = json.Unmarshal([]byte(form.Query), &query)
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Invalid query",
Message: err.Error(),
})
return out
}
err = json.Unmarshal([]byte(form.Fields), &projection)
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Invalid projection",
Message: err.Error(),
})
return out
}
err = json.Unmarshal([]byte(form.Sort), &sort)
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Invalid sort",
Message: err.Error(),
})
return out
}
opt := mongoOptions.FindOptions{
Limit: &form.Limit,
Projection: projection,
Skip: &form.Skip,
Sort: sort,
}
total, err := client.Database(dbKey).Collection(collKey).CountDocuments(ctx, query, nil)
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Encountered an error while counting documents",
Message: err.Error(),
})
return out
}
cur, err := client.Database(dbKey).Collection(collKey).Find(ctx, query, &opt)
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Encountered an error while performing query",
Message: err.Error(),
})
return out
}
defer cur.Close(ctx)
var results []bson.M
err = cur.All(ctx, &results)
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Encountered an error while performing query",
Message: err.Error(),
})
return out
}
out.Results = results
out.Total = total
return out
}

View File

@ -0,0 +1,49 @@
package app
import (
"encoding/json"
"fmt"
"strings"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
func (a *App) PerformInsert(hostKey, dbKey, collKey, jsonData string) interface{} {
var data []interface{}
jsonData = strings.TrimSpace(jsonData)
if strings.HasPrefix(jsonData, "{") {
jsonData = "[" + jsonData + "]"
}
err := json.Unmarshal([]byte(jsonData), &data)
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Couldn't parse JSON",
Message: err.Error(),
})
return nil
}
client, ctx, close, err := a.connectToHost(hostKey)
if err != nil {
fmt.Println(err.Error())
return nil
}
defer close()
res, err := client.Database(dbKey).Collection(collKey).InsertMany(ctx, data)
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Encountered an error while performing query",
Message: err.Error(),
})
return nil
}
return res.InsertedIDs
}

View File

@ -0,0 +1,28 @@
package app
import (
"fmt"
"github.com/wailsapp/wails/v2/pkg/runtime"
"go.mongodb.org/mongo-driver/bson"
)
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
}

59
internal/app/database.go Normal file
View File

@ -0,0 +1,59 @@
package app
import (
"fmt"
"github.com/wailsapp/wails/v2/pkg/runtime"
"go.mongodb.org/mongo-driver/bson"
)
func (a *App) OpenDatabase(hostKey, dbKey string) (collections []string) {
client, ctx, close, err := a.connectToHost(hostKey)
if err != nil {
fmt.Println(err.Error())
return nil
}
collections, err = client.Database(dbKey).ListCollectionNames(ctx, bson.D{})
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Could not retrieve collection list for " + dbKey,
Message: err.Error(),
})
return nil
}
defer close()
return collections
}
func (a *App) DropDatabase(hostKey, dbKey string) bool {
sure, _ := runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Title: "Confirm",
Message: "Are you sure you want to drop " + dbKey + "?",
Buttons: []string{"yes", "no"},
DefaultButton: "Yes",
CancelButton: "No",
})
if sure != "Yes" {
return false
}
client, ctx, close, err := a.connectToHost(hostKey)
if err != nil {
fmt.Println(err.Error())
return false
}
err = client.Database(dbKey).Drop(ctx)
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Could not drop " + dbKey,
Message: err.Error(),
})
return false
}
defer close()
return true
}

58
internal/app/host.go Normal file
View File

@ -0,0 +1,58 @@
package app
import (
"context"
"errors"
"fmt"
"time"
"github.com/wailsapp/wails/v2/pkg/runtime"
"go.mongodb.org/mongo-driver/mongo"
mongoOptions "go.mongodb.org/mongo-driver/mongo/options"
)
type Host struct {
Name string `json:"name"`
URI string `json:"uri"`
}
var hosts = map[string]Host{
"localhost": {Name: "Localhost", URI: "mongodb://localhost:27017"},
"tig": {Name: "cmdb.myinfra.nl"},
"vbt": {Name: "vbtverhuurmakelaars.nl"},
}
func (a *App) Hosts() map[string]Host {
return hosts
}
func (a *App) connectToHost(hostKey string) (*mongo.Client, context.Context, func(), error) {
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",
Message: "Failed to establish a connection with " + h.Name,
})
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
}

322
main.go
View File

@ -1,337 +1,19 @@
package main
import (
"context"
"embed"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/garraflavatra/mongodup/internal/app"
"github.com/wailsapp/wails/v2"
"github.com/wailsapp/wails/v2/pkg/options"
"github.com/wailsapp/wails/v2/pkg/options/assetserver"
"github.com/wailsapp/wails/v2/pkg/runtime"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
mongoOptions "go.mongodb.org/mongo-driver/mongo/options"
)
//go:embed all:frontend/dist
var assets embed.FS
type Host struct {
Name string `json:"name"`
URI string `json:"uri"`
}
var hosts = map[string]Host{
"localhost": {Name: "Localhost", URI: "mongodb://localhost:27017"},
"tig": {Name: "cmdb.myinfra.nl"},
"vbt": {Name: "vbtverhuurmakelaars.nl"},
}
type App struct {
ctx context.Context
}
func NewApp() *App {
return &App{}
}
func (a *App) Startup(ctx context.Context) {
a.ctx = ctx
}
func (a *App) Hosts() map[string]Host {
return hosts
}
func (a *App) connectToHost(hostKey string) (*mongo.Client, context.Context, func(), error) {
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",
Message: "Failed to establish a connection with " + h.Name,
})
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
}
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
}
func (a *App) OpenDatabase(hostKey, dbKey string) (collections []string) {
client, ctx, close, err := a.connectToHost(hostKey)
if err != nil {
fmt.Println(err.Error())
return nil
}
collections, err = client.Database(dbKey).ListCollectionNames(ctx, bson.D{})
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Could not retrieve collection list for " + dbKey,
Message: err.Error(),
})
return nil
}
defer close()
return collections
}
func (a *App) DropDatabase(hostKey, dbKey string) bool {
sure, _ := runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Title: "Confirm",
Message: "Are you sure you want to drop " + dbKey + "?",
Buttons: []string{"yes", "no"},
DefaultButton: "Yes",
CancelButton: "No",
})
if sure != "Yes" {
return false
}
client, ctx, close, err := a.connectToHost(hostKey)
if err != nil {
fmt.Println(err.Error())
return false
}
err = client.Database(dbKey).Drop(ctx)
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Could not drop " + dbKey,
Message: err.Error(),
})
return false
}
defer close()
return true
}
func (a *App) OpenCollection(hostKey, dbKey, collKey string) (result bson.M) {
client, ctx, close, err := a.connectToHost(hostKey)
if err != nil {
fmt.Println(err.Error())
return nil
}
command := bson.M{"collStats": collKey}
err = client.Database(dbKey).RunCommand(ctx, command).Decode(&result)
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Could not retrieve collection list for " + dbKey,
Message: err.Error(),
})
return nil
}
defer close()
return result
}
type findResult struct {
Total int64 `json:"total"`
Results interface{} `json:"results"`
}
func (a *App) PerformFind(hostKey, dbKey, collKey string, formJson string) findResult {
var out findResult
var form struct {
Fields string `json:"fields"`
Limit int64 `json:"limit"`
Query string `json:"query"`
Skip int64 `json:"skip"`
Sort string `json:"sort"`
}
err := json.Unmarshal([]byte(formJson), &form)
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Couldn't parse form",
Message: err.Error(),
})
return out
}
client, ctx, close, err := a.connectToHost(hostKey)
if err != nil {
fmt.Println(err.Error())
return out
}
defer close()
var query bson.M
var projection bson.M
var sort bson.M
err = json.Unmarshal([]byte(form.Query), &query)
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Invalid query",
Message: err.Error(),
})
return out
}
err = json.Unmarshal([]byte(form.Fields), &projection)
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Invalid projection",
Message: err.Error(),
})
return out
}
err = json.Unmarshal([]byte(form.Sort), &sort)
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Invalid sort",
Message: err.Error(),
})
return out
}
opt := mongoOptions.FindOptions{
Limit: &form.Limit,
Projection: projection,
Skip: &form.Skip,
Sort: sort,
}
total, err := client.Database(dbKey).Collection(collKey).CountDocuments(ctx, query, nil)
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Encountered an error while counting documents",
Message: err.Error(),
})
return out
}
cur, err := client.Database(dbKey).Collection(collKey).Find(ctx, query, &opt)
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Encountered an error while performing query",
Message: err.Error(),
})
return out
}
defer cur.Close(ctx)
var results []bson.M
err = cur.All(ctx, &results)
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Encountered an error while performing query",
Message: err.Error(),
})
return out
}
out.Results = results
out.Total = total
return out
}
func (a *App) PerformInsert(hostKey, dbKey, collKey, jsonData string) interface{} {
var data []interface{}
jsonData = strings.TrimSpace(jsonData)
if strings.HasPrefix(jsonData, "{") {
jsonData = "[" + jsonData + "]"
}
err := json.Unmarshal([]byte(jsonData), &data)
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Couldn't parse JSON",
Message: err.Error(),
})
return nil
}
client, ctx, close, err := a.connectToHost(hostKey)
if err != nil {
fmt.Println(err.Error())
return nil
}
defer close()
res, err := client.Database(dbKey).Collection(collKey).InsertMany(ctx, data)
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Encountered an error while performing query",
Message: err.Error(),
})
return nil
}
return res.InsertedIDs
}
func main() {
app := NewApp()
app := app.NewApp()
err := wails.Run(&options.App{
Title: "Mongodup",