Skip to content

Commit 39ad596

Browse files
committed
Refactor and add database test
1 parent 05c406e commit 39ad596

12 files changed

Lines changed: 352 additions & 193 deletions

File tree

‎.env.example‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
DATABASE_TYPE=<mongo|dynamo>
2+
MONGO_USER=user
3+
MONGO_PASS=<password>
4+
MONGO_HOST=<host>:<port>
5+
MONGO_NAME=admin

‎.gitignore‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
.realize.yaml
22
data/
3-
github-analyser
3+
github-analyser
4+
.env

‎app/app.go‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package app
2+
3+
import (
4+
"net/http"
5+
6+
"github.com/go-chi/chi"
7+
8+
"github.com/go-chi/chi/middleware"
9+
"github.com/rs/cors"
10+
)
11+
12+
func InitRouter(apiPath string) *chi.Mux {
13+
14+
router := chi.NewRouter()
15+
16+
router.Use(middleware.RequestID)
17+
router.Use(middleware.RealIP)
18+
router.Use(middleware.Logger)
19+
router.Use(middleware.Recoverer)
20+
21+
router.HandleFunc(apiPath, checkAPI)
22+
23+
return router
24+
}
25+
26+
func HandleCors(h http.Handler) http.Handler {
27+
28+
cors := cors.New(cors.Options{
29+
AllowedOrigins: []string{"*"},
30+
AllowCredentials: true,
31+
AllowedHeaders: []string{"Content-Type", "*"},
32+
Debug: false,
33+
})
34+
handler := cors.Handler(h)
35+
return handler
36+
37+
}

‎app/routes.go‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package app
2+
3+
import (
4+
"context"
5+
"log"
6+
"net/http"
7+
"time"
8+
9+
"github.com/globalsign/mgo/bson"
10+
"github.com/m-lukas/github-analyser/db"
11+
"go.mongodb.org/mongo-driver/bson/primitive"
12+
)
13+
14+
func checkAPI(w http.ResponseWriter, r *http.Request) {
15+
db, err := db.Get()
16+
if err != nil {
17+
log.Fatal("Unable to establish database connection!")
18+
}
19+
collection := db.Collection("testing")
20+
21+
result := struct {
22+
ID primitive.ObjectID `bson:"_id,omitempty"`
23+
Value string `bson:"Value"`
24+
}{}
25+
26+
objectID, err := primitive.ObjectIDFromHex("5cab24edf3f1a30a16927aeb")
27+
if err != nil {
28+
log.Fatal("Could not convert test object id!")
29+
}
30+
31+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
32+
defer cancel()
33+
data := collection.FindOne(ctx, bson.M{"_id": objectID})
34+
35+
err = data.Decode(&result)
36+
if err != nil {
37+
log.Fatal("Error while decoding mongo document data!")
38+
}
39+
w.Write([]byte(result.Value))
40+
}

‎db/config.go‎

Lines changed: 0 additions & 87 deletions
This file was deleted.

‎db/db.go‎

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
package db
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"log"
7+
"os"
8+
"time"
9+
10+
"go.mongodb.org/mongo-driver/mongo"
11+
"go.mongodb.org/mongo-driver/mongo/options"
12+
"go.mongodb.org/mongo-driver/mongo/readpref"
13+
)
14+
15+
var dbInstance *Database
16+
17+
type Database struct {
18+
MongoClient *mongo.Client
19+
Config *DatabaseConfig
20+
}
21+
22+
type DatabaseConfig struct {
23+
MongoDatabaseName string
24+
}
25+
26+
func defaultDatabaseConfig() *DatabaseConfig {
27+
return &DatabaseConfig{
28+
MongoDatabaseName: "core",
29+
}
30+
}
31+
32+
func Init() error {
33+
dbInstance = &Database{
34+
Config: defaultDatabaseConfig(),
35+
}
36+
37+
mongoClient, err := initMongoClient()
38+
if err != nil {
39+
return err
40+
}
41+
42+
dbInstance.MongoClient = mongoClient
43+
return nil
44+
}
45+
46+
/*
47+
Returns default mongo database.
48+
*/
49+
func Get() (*mongo.Database, error) {
50+
51+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
52+
defer cancel()
53+
err := dbInstance.MongoClient.Ping(ctx, readpref.Primary())
54+
55+
if err == nil {
56+
client := dbInstance.MongoClient
57+
config := dbInstance.Config
58+
return client.Database(config.MongoDatabaseName), nil
59+
}
60+
61+
mongoClient, err := initMongoClient()
62+
if err != nil {
63+
return nil, err
64+
}
65+
66+
dbInstance.MongoClient = mongoClient
67+
68+
client := dbInstance.MongoClient
69+
config := dbInstance.Config
70+
return client.Database(config.MongoDatabaseName), nil
71+
}
72+
73+
/*
74+
Initializes the mongoDB Client to access databases and collections.
75+
*/
76+
func initMongoClient() (*mongo.Client, error) {
77+
78+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
79+
defer cancel()
80+
client, err := mongo.Connect(ctx, options.Client().ApplyURI(getMongoDBConfig()))
81+
if err != nil {
82+
return nil, err
83+
}
84+
85+
err = client.Ping(ctx, readpref.Primary())
86+
if err != nil {
87+
return nil, err
88+
}
89+
90+
log.Println("Initialized mongo client!")
91+
return client, err
92+
93+
}
94+
95+
/*
96+
Returns configurated URI string for MongoDB.
97+
*/
98+
func getMongoDBConfig() (uri string) {
99+
dbHost := os.Getenv("MONGO_HOST")
100+
dbName := os.Getenv("MONGO_NAME")
101+
dbUser := os.Getenv("MONGO_USER")
102+
dbPass := os.Getenv("MONGO_PASS")
103+
104+
return fmt.Sprintf(`mongodb://%s:%s@%s/%s`, dbUser, dbPass, dbHost, dbName)
105+
}

‎github-analyser‎

34.3 KB
Binary file not shown.

‎main.go‎

Lines changed: 0 additions & 66 deletions
This file was deleted.
Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,6 @@ server:
2323
schema:
2424
- name: github-analyser
2525
path: /Users/m-lukas/Documents/Projects/go/src/github.com/m-lukas/github-analyser
26-
env:
27-
DATABASE_TYPE: <mongo/dynamo>
28-
MONGO_USER: <user>
29-
MONGO_PASS: <password>
30-
MONGO_HOST: <host&port>
31-
MONGO_NAME: admin
3226
commands:
3327
fmt:
3428
status: true

0 commit comments

Comments
 (0)