Skip to content

Commit 1ee5d9f

Browse files
author
xbucks
committed
everything works
1 parent 11755d5 commit 1ee5d9f

13 files changed

+255
-34
lines changed

go.mod

+2
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ require (
1616
require (
1717
github.com/BurntSushi/toml v1.1.0 // indirect
1818
github.com/KyleBanks/depth v1.2.1 // indirect
19+
github.com/acobaugh/osrelease v0.0.0-20181218015638-a93a0a55a249 // indirect
1920
github.com/fsnotify/fsnotify v1.5.4 // indirect
2021
github.com/gin-contrib/pprof v1.3.0 // indirect
2122
github.com/gin-contrib/sse v0.1.0 // indirect
@@ -49,6 +50,7 @@ require (
4950
github.com/spf13/cast v1.5.0 // indirect
5051
github.com/spf13/jwalterweatherman v1.1.0 // indirect
5152
github.com/spf13/pflag v1.0.5 // indirect
53+
github.com/strikesecurity/strikememongo v0.2.4 // indirect
5254
github.com/subosito/gotenv v1.3.0 // indirect
5355
github.com/ugorji/go/codec v1.2.7 // indirect
5456
github.com/xdg-go/pbkdf2 v1.0.0 // indirect

go.sum

+69
Large diffs are not rendered by default.

internal/db/dbconnection_test.go

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package db
2+
3+
import (
4+
"context"
5+
"os"
6+
"testing"
7+
"time"
8+
9+
"github.com/rs/zerolog/log"
10+
"github.com/stretchr/testify/assert"
11+
"github.com/strikesecurity/strikememongo"
12+
"go.mongodb.org/mongo-driver/mongo"
13+
"go.mongodb.org/mongo-driver/mongo/options"
14+
)
15+
16+
var (
17+
TestDataBase *mongo.Database
18+
)
19+
20+
func TestMain(m *testing.M) {
21+
mongoServer, err := strikememongo.Start("4.0.5") // TODO: Only this version works, figure out why ?
22+
if err != nil {
23+
log.Fatal().Err(err)
24+
}
25+
defer mongoServer.Stop()
26+
27+
client, err := mongo.NewClient(options.Client().ApplyURI(mongoServer.URI()))
28+
if err != nil {
29+
return
30+
}
31+
32+
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
33+
defer cancel()
34+
err = client.Connect(ctx)
35+
if err != nil {
36+
log.Fatal().Err(err)
37+
}
38+
TestDataBase = client.Database(strikememongo.RandomDatabase())
39+
OverrideDBSetup(client, TestDataBase)
40+
// insertTestData()
41+
42+
os.Exit(m.Run())
43+
}
44+
45+
/*
46+
func insertTestData() {
47+
data, _ := ioutil.ReadFile("../mockdata/issues_response.json")
48+
issues, _ := util.UnMarshalIssuesResponse(data)
49+
db, err := GetDB()
50+
if err != nil {
51+
log.Panic().Err(err).Msg("database is not initialized")
52+
}
53+
dSvc := NewOrderDataService(db)
54+
for _, m := range *issues {
55+
_, _ = dSvc.CreateOne(&m)
56+
}
57+
}
58+
*/
59+
60+
func TestDBSuccess(t *testing.T) {
61+
db, err := GetDB()
62+
assert.Nil(t, err)
63+
assert.NotNil(t, db)
64+
assert.IsType(t, *db, mongo.Database{})
65+
}
66+
67+
func TestDBClient(t *testing.T) {
68+
client, err := GetDBClient()
69+
assert.Nil(t, err)
70+
assert.NotNil(t, client)
71+
assert.IsType(t, *client, mongo.Client{})
72+
}

internal/db/orders.repo.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ type OrdersDataService struct {
3636
collection *mongo.Collection
3737
}
3838

39-
func NewIssueDataService(db MongoDBDatabase) *OrdersDataService {
39+
func NewOrderDataService(db MongoDBDatabase) *OrdersDataService {
4040
iDBSvc := &OrdersDataService{
4141
collection: db.Collection(OrdersCollection),
4242
}
@@ -82,12 +82,12 @@ func (ordDataSvc *OrdersDataService) Update(purchaseOrder *models.Order) (int64,
8282
}
8383

8484
if result.MatchedCount != 0 {
85-
log.Info().Str("OrderId", result.UpsertedID.(string)).Msg("matched and replaced an existing document")
85+
log.Info().Msg("matched and replaced an existing document")
8686
return result.MatchedCount, nil
8787
}
8888

8989
if result.UpsertedCount != 0 {
90-
log.Info().Str("OrderId", result.UpsertedID.(string)).Msg("inserted a new order with ID")
90+
log.Info().Msg("inserted a new order with ID")
9191
return result.MatchedCount, nil
9292
}
9393

internal/handlers/orders.handler.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ type OrdersHandler struct {
1818

1919
func NewOrdersHandler(database db.MongoDBDatabase) *OrdersHandler {
2020
ic := &OrdersHandler{
21-
dataSvc: db.NewIssueDataService(database),
21+
dataSvc: db.NewOrderDataService(database),
2222
}
2323
return ic
2424
}
+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
package handlers

internal/handlers/seed.handler.go

+14-7
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,22 @@ import (
1212
)
1313

1414
const (
15-
SEED_RECORD_COUNT = 50
15+
SeedRecordCount = 500
1616
)
1717

18-
type SeedDBController struct {
19-
DBService db.OrdersDataService
18+
type SeedHandler struct {
19+
dataSvc db.DataService
2020
}
2121

22-
func (seedController *SeedDBController) SeedDB(c *gin.Context) {
23-
for i := 0; i < SEED_RECORD_COUNT; i++ {
22+
func NewSeedHandler(database db.MongoDBDatabase) *SeedHandler {
23+
ic := &SeedHandler{
24+
dataSvc: db.NewOrderDataService(database),
25+
}
26+
return ic
27+
}
28+
29+
func (sHandler *SeedHandler) SeedDB(c *gin.Context) {
30+
for i := 0; i < SeedRecordCount; i++ {
2431
product := []models.Product{
2532
{
2633
Name: faker.Name(),
@@ -39,7 +46,7 @@ func (seedController *SeedDBController) SeedDB(c *gin.Context) {
3946
po := &models.Order{
4047
Products: product,
4148
}
42-
_, err := seedController.DBService.Create(po)
49+
_, err := sHandler.dataSvc.Create(po)
4350
if err != nil {
4451
c.JSON(http.StatusInternalServerError, gin.H{
4552
"message": "Unable inserted data",
@@ -50,6 +57,6 @@ func (seedController *SeedDBController) SeedDB(c *gin.Context) {
5057

5158
c.JSON(http.StatusOK, gin.H{
5259
"message": "Successfully inserted fake data",
53-
"Count": SEED_RECORD_COUNT,
60+
"Count": SeedRecordCount,
5461
})
5562
}

internal/app/server/router.go internal/server/router.go

+7-7
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@ func WebRouter(svcInfo *models.ServiceInfo, client handlers.MongoDBClient, db db
3333

3434
// Seed DB
3535
if util.IsDevMode(svcInfo.Environment) {
36-
seed := new(handlers.SeedDBController)
37-
router.POST("/seedDB", seed.SeedDB)
36+
seed := handlers.NewSeedHandler(db)
37+
router.POST("/seedDB", seed.SeedDB) // /seedDB
3838
}
3939

4040
// Routes - API
@@ -43,11 +43,11 @@ func WebRouter(svcInfo *models.ServiceInfo, client handlers.MongoDBClient, db db
4343
ordersGroup := v1.Group("orders")
4444
{
4545
orders := handlers.NewOrdersHandler(db)
46-
ordersGroup.GET("/", orders.GetAll) // api/v1/orders
47-
ordersGroup.GET("/:id", orders.GetById) // api/v1/orders/{id}
48-
ordersGroup.POST("/", orders.Post) // api/v1/orders
49-
ordersGroup.PUT("/", orders.Post) // api/v1/orders
50-
ordersGroup.DELETE("/:id", orders.DeleteById) // api/v1/orders/{id}
46+
ordersGroup.GET("", orders.GetAll) // api/v1/orders
47+
ordersGroup.GET("/:id", orders.GetById) // api/v1/orders/:id
48+
ordersGroup.POST("", orders.Post) // api/v1/orders
49+
ordersGroup.PUT("", orders.Post) // api/v1/orders
50+
ordersGroup.DELETE("/:id", orders.DeleteById) // api/v1/orders/:id
5151
}
5252
}
5353

internal/server/router_test.go

+80
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package server
2+
3+
import (
4+
"context"
5+
"github.com/rameshsunkara/go-rest-api-example/internal/models"
6+
"net/http"
7+
"testing"
8+
"time"
9+
10+
"github.com/gin-gonic/gin"
11+
"go.mongodb.org/mongo-driver/mongo"
12+
"go.mongodb.org/mongo-driver/mongo/options"
13+
"go.mongodb.org/mongo-driver/mongo/readpref"
14+
)
15+
16+
var (
17+
svcInfo = &models.ServiceInfo{
18+
Name: "test-api-service",
19+
Version: "rams-fav",
20+
UpTime: time.Now(),
21+
Environment: "test",
22+
}
23+
)
24+
25+
type MockMongoDBClient struct{}
26+
27+
func (m *MockMongoDBClient) Ping(ctx context.Context, rp *readpref.ReadPref) error {
28+
return nil
29+
}
30+
31+
type MockMongoDataBase struct{}
32+
33+
func (m *MockMongoDataBase) Collection(name string, opts ...*options.CollectionOptions) *mongo.Collection {
34+
return nil
35+
}
36+
37+
func TestListOfRoutes(t *testing.T) {
38+
router := WebRouter(svcInfo, &MockMongoDBClient{}, &MockMongoDataBase{})
39+
list := router.Routes()
40+
41+
assertRoutePresent(t, list, gin.RouteInfo{
42+
Method: http.MethodGet,
43+
Path: "/status",
44+
})
45+
46+
assertRoutePresent(t, list, gin.RouteInfo{
47+
Method: http.MethodGet,
48+
Path: "/api/v1/orders",
49+
})
50+
51+
assertRoutePresent(t, list, gin.RouteInfo{
52+
Method: http.MethodGet,
53+
Path: "/api/v1/orders/:id",
54+
})
55+
56+
assertRoutePresent(t, list, gin.RouteInfo{
57+
Method: http.MethodPost,
58+
Path: "/api/v1/orders",
59+
})
60+
61+
assertRoutePresent(t, list, gin.RouteInfo{
62+
Method: http.MethodPut,
63+
Path: "/api/v1/orders",
64+
})
65+
66+
assertRoutePresent(t, list, gin.RouteInfo{
67+
Method: http.MethodDelete,
68+
Path: "/api/v1/orders/:id",
69+
})
70+
71+
}
72+
73+
func assertRoutePresent(t *testing.T, gotRoutes gin.RoutesInfo, wantRoute gin.RouteInfo) {
74+
for _, gotRoute := range gotRoutes {
75+
if gotRoute.Path == wantRoute.Path && gotRoute.Method == wantRoute.Method {
76+
return
77+
}
78+
}
79+
t.Errorf("route not found: %v", wantRoute)
80+
}
File renamed without changes.

main.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,14 @@ package main
22

33
import (
44
"flag"
5+
"github.com/rameshsunkara/go-rest-api-example/internal/server"
56
"github.com/rameshsunkara/go-rest-api-example/pkg/util"
67
"github.com/rs/zerolog"
78
"github.com/rs/zerolog/pkgerrors"
89
"os"
910
"time"
1011

1112
_ "github.com/rameshsunkara/go-rest-api-example/docs"
12-
"github.com/rameshsunkara/go-rest-api-example/internal/app/server"
1313
"github.com/rameshsunkara/go-rest-api-example/internal/config"
1414
"github.com/rameshsunkara/go-rest-api-example/internal/db"
1515
"github.com/rameshsunkara/go-rest-api-example/internal/models"

Orders.postman_collection.json ordersapi.postman_collection.json

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"info": {
33
"_postman_id": "4513b26b-eb10-4cca-886a-7704799f9a51",
4-
"name": "Orders",
4+
"name": "ordersapi",
55
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
66
"_exporter_id": "1129965"
77
},
@@ -12,13 +12,13 @@
1212
"method": "GET",
1313
"header": [],
1414
"url": {
15-
"raw": "{{host}}:{{port}}/health",
15+
"raw": "{{host}}:{{port}}/status",
1616
"host": [
1717
"{{host}}"
1818
],
1919
"port": "{{port}}",
2020
"path": [
21-
"health"
21+
"status"
2222
]
2323
}
2424
},
@@ -50,7 +50,7 @@
5050
"method": "GET",
5151
"header": [],
5252
"url": {
53-
"raw": "{{host}}:{{port}}/api/v1/orders/628c556112951bff10538abc",
53+
"raw": "{{host}}:{{port}}/api/v1/orders/629536b3fac02728de50c042",
5454
"host": [
5555
"{{host}}"
5656
],
@@ -59,7 +59,7 @@
5959
"api",
6060
"v1",
6161
"orders",
62-
"628c556112951bff10538abc"
62+
"629536b3fac02728de50c042"
6363
]
6464
}
6565
},

tmp/go-rest-api-example.pid

-10
This file was deleted.

0 commit comments

Comments
 (0)