Commit 0201afc0 authored by Max Richter's avatar Max Richter
Browse files

style(mongo): rename db.go to main.go

parent 355b31c2
package mongo
import (
"context"
"log"
"os"
"strings"
"time"
repos "git.coco.study/fvitt/good2go/database/mongo/repositories"
"git.coco.study/fvitt/good2go/internal/model"
_ "github.com/joho/godotenv/autoload"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"gopkg.in/mgo.v2/bson"
)
func getEnv(variableName string, defaultValue string) string {
envValue := os.Getenv(variableName)
if envValue == "" {
return defaultValue
}
return envValue
}
func createDBClient(mongoURL string) (client *mongo.Client, ctx context.Context) {
client, err := mongo.NewClient(options.Client().ApplyURI(mongoURL))
if err != nil {
log.Fatal(err)
}
ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
if err != nil {
log.Fatal("[MONGODB]", err)
}
log.Println("[MONGODB] connecting to " + mongoURL + "...")
err = client.Ping(ctx, readpref.Primary())
if err != nil {
log.Fatal(err)
} else {
log.Println("[MONGODB] connected")
databases, err := client.ListDatabaseNames(ctx, bson.M{})
if err != nil {
log.Fatal(err)
}
log.Print("[MONGODB] databases: [" + strings.Join(databases, ",") + "]")
}
return client, ctx
}
// Init initializes connection to a database
// and connects all the individual repositories to their collections
func Init() {
// Create a mongodb client
client, ctx := createDBClient(getEnv("MONGO_URL", "mongodb://127.0.0.1:27017"))
defer client.Disconnect(ctx)
// Connect to a specified database
db := client.Database(getEnv("MONGO_DB", "good2go"))
// Connect the repositories
repos.RoomRepository.ConnectTo(ctx, db.Collection("rooms"))
room := &model.Room{
Number: 420,
Capacity: 69,
}
repos.RoomRepository.CreateRoom(room)
rooms := repos.RoomRepository.GetAllRooms()
log.Print(rooms)
}
package mongo
import (
"log"
"time"
repos "git.coco.study/fvitt/good2go/database/mongo/repositories"
utils "git.coco.study/fvitt/good2go/database/mongo/utils"
)
var (
// RoomRepository does crud stuff
roomRepo = repos.RoomRepository
)
// Init initializes connection to a database
// and connects all the individual repositories to their collections
func Init() {
// Create a mongodb client
client, ctx := utils.CreateDBClient(10 * time.Second)
defer client.Disconnect(ctx)
// Connect to a specified database
db := client.Database(utils.GetDBName())
// Connect the repositories
repos.RoomRepository.ConnectTo(db.Collection("rooms"))
log.Print("All rooms", roomRepo.GetAllRooms())
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment