Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Sign in
Toggle navigation
Menu
Open sidebar
Fabian Vitt
good2go
Commits
fb64e205
Commit
fb64e205
authored
Jun 03, 2020
by
Max Richter
Browse files
feat(mongodb): created main db init func
parent
92769100
Changes
1
Hide whitespace changes
Inline
Side-by-side
database/mongo/db.go
0 → 100644
View file @
fb64e205
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
)
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment