Initial commit

This commit is contained in:
Kevin Kandlbinder 2022-02-20 23:42:32 +01:00
commit b81af24e50
21 changed files with 2283 additions and 0 deletions

61
internal/db/db.go Normal file
View file

@ -0,0 +1,61 @@
package db
import (
"context"
"github.com/Unkn0wnCat/matrix-veles/internal/db/model"
"github.com/spf13/viper"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
"time"
)
var DbClient *mongo.Client
func Connect() {
if viper.GetString("bot.mongo.uri") == "" {
log.Println("Skipping database login...")
return
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
newClient, err := mongo.Connect(ctx, options.Client().ApplyURI(viper.GetString("bot.mongo.uri")))
if err != nil {
log.Println("Could not connect to DB")
log.Panicln(err)
}
DbClient = newClient
}
func SaveEntry(entry *model.DBEntry) error {
db := DbClient.Database(viper.GetString("bot.mongo.database"))
opts := options.Replace().SetUpsert(true)
filter := bson.D{{"_id", entry.ID}}
_, err := db.Collection("entries").ReplaceOne(context.TODO(), filter, entry, opts)
return err
}
func GetEntryByHash(hash string) (*model.DBEntry, error) {
db := DbClient.Database(viper.GetString("bot.mongo.database"))
res := db.Collection("entries").FindOne(context.TODO(), bson.D{{"hash_value", hash}})
if res.Err() != nil {
return nil, res.Err()
}
object := model.DBEntry{}
err := res.Decode(&object)
if err != nil {
return nil, err
}
return &object, nil
}

View file

@ -0,0 +1,21 @@
package model
import (
"go.mongodb.org/mongo-driver/bson/primitive"
"time"
)
type DBEntry struct {
ID primitive.ObjectID `bson:"_id" json:"id"`
Tags []string `bson:"tags" json:"tags"`
HashValue string `bson:"hash_value" json:"hash"`
FileURL string `bson:"file_url" json:"file_url"`
Timestamp time.Time `bson:"timestamp" json:"timestamp"`
AddedBy *primitive.ObjectID `bson:"added_by" json:"added_by"`
Comments []*DBEntryComment `bson:"comments" json:"comments"`
}
type DBEntryComment struct {
CommentedBy *primitive.ObjectID `bson:"commented_by" json:"commented_by"`
Content string `bson:"content" json:"content"`
}