Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(bug-fixes): server errors with bson tags fixed #5

Merged
merged 6 commits into from
Dec 18, 2023
Merged
45 changes: 21 additions & 24 deletions src/api/basketball/controllers/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func UploadTeamPlayer(w http.ResponseWriter, r *http.Request) {
fmt.Println("Request Incoming")
var player playerModel.Player
_ = json.NewDecoder(r.Body).Decode(&player)
fmt.Println("player", player)
fmt.Println("player points ::", player.Points)
insertedVal := helper.UploadTeamPlayer(player)

var res = map[string]*mongo.InsertOneResult{
Expand All @@ -39,31 +39,28 @@ func UploadTeamPlayer(w http.ResponseWriter, r *http.Request) {
}

func UpdateTeamPlayer(w http.ResponseWriter, r *http.Request) {
fmt.Println("Update Request Incoming.")
var updatePlayer playerModel.Player
_ = json.NewDecoder(r.Body).Decode(&updatePlayer)

res := map[string]interface{}{}
var requestBody struct {
Name string `json:"name"`
IncrementPoint int `json:"incrementPoint"`
IncrementAssist int `json:"incrementAssist"`
}

err := json.NewDecoder(r.Body).Decode(&requestBody)
fmt.Println(requestBody)

if err != nil {
http.Error(w, "Error decoding request body: "+err.Error(), http.StatusBadRequest)
return
}
player, err := helper.GetPlayerByName(requestBody.Name)

for key, val := range map[string]interface{}{
"Name": updatePlayer.Name,
"ID": updatePlayer.ID,
"ImageLink": updatePlayer.ImageLink,
"Position": updatePlayer.Position,
"Branch": updatePlayer.Branch,
"Year": updatePlayer.Year,
"Age": updatePlayer.Age,
"Instagram": updatePlayer.Instagram,
"Minutes": updatePlayer.Minutes,
"Rebounds": updatePlayer.Rebounds,
"Assists": updatePlayer.Assists,
"Points": updatePlayer.Points,
} {
if val == 0 || val == "" {
continue
}
res[key] = val
if err != nil {
http.Error(w, "Error fetching player from the database: "+err.Error(), http.StatusInternalServerError)
return
}
player = helper.IncrementPlayerStats(player, requestBody)
updatedPlayer := helper.UpdateTeamPlayer(player)

json.NewEncoder(w).Encode(updatePlayer)
json.NewEncoder(w).Encode(updatedPlayer)
}
4 changes: 2 additions & 2 deletions src/api/basketball/database/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ var Collection *mongo.Collection
// Initiator function which runs automatically at the start of application
// This function connects to the DB and returns collection instances which is used for DB actions.
func init() {
const connectionString = "mongodb+srv://linux-skg:[email protected]/?retryWrites=true&w=majority"
const connectionString = "mongodb+srv://linux-skg:[email protected]/?retryWrites=true&w=majoritymongodb+srv://linux-skg:[email protected]/?retryWrites=true&w=majority"
const databaseName = "basketball"
const collection1_Name = "in-match-scoring"
const collection1_Name = "teams"

clientOptions := options.Client().ApplyURI(connectionString)
client, err := mongo.Connect(context.TODO(), clientOptions)
Expand Down
84 changes: 54 additions & 30 deletions src/api/basketball/helper/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,15 @@ import (
@Params:
team string --> extracted from URL
*/
func TeamWisePlayers(team string) []primitive.M {
func TeamWisePlayers(branch string) []primitive.M {

//creating a cursor instance for query's matching documents
cur, err := basketballdb.Collection.Find(context.Background(), bson.D{{Key: "team", Value: team}})
cur, err := basketballdb.Collection.Find(context.Background(), bson.D{{Key: "branch", Value: branch}})

//handling error
if err != nil {
log.Fatal("Error:", err)
}

// data structure to be sent as response
var Players []primitive.M

Expand Down Expand Up @@ -57,45 +56,70 @@ func TeamWisePlayers(team string) []primitive.M {
}

func UploadTeamPlayer(player playerModel.Player) *mongo.InsertOneResult {
fmt.Println("Recv UTP ::",player);
inserted, err := basketballdb.Collection.InsertOne(context.TODO(), player)

if err != nil {
log.Fatal("Error occured while inserting in db @helper/UploadTeamPlayer")
log.Fatal("Error occured while inserting in db @helper/UploadTeamPlayer",err)
}

fmt.Println("Registration Done :", inserted)

return inserted
}

func UpdateTeamPlayer(updatePlayer playerModel.Player) {

res := map[string]interface{}{}

for key, val := range map[string]interface{}{
"Name": updatePlayer.Name,
"ID": updatePlayer.ID,
"ImageLink": updatePlayer.ImageLink,
"Position": updatePlayer.Position,
"Branch": updatePlayer.Branch,
"Year": updatePlayer.Year,
"Age": updatePlayer.Age,
"Instagram": updatePlayer.Instagram,
"Minutes": updatePlayer.Minutes,
"Rebounds": updatePlayer.Rebounds,
"Assists": updatePlayer.Assists,
"Points": updatePlayer.Points,
} {
if val == 0 || val == "" {
continue
func GetPlayerByName(name string) (playerModel.Player, error) {
var player playerModel.Player

// Construct the filter
filter := bson.D{{Key: "name", Value: name}}

// Find the player in the database
result := basketballdb.Collection.FindOne(context.Background(), filter)
if result.Err() != nil {
if result.Err() == mongo.ErrNoDocuments {
fmt.Println("Player not found")
return player, fmt.Errorf("Player not found")
}
fmt.Println("Key , Value:", key, val)
res[key] = val
log.Println("Error finding player:", result.Err())
return player, result.Err()
}
// Decode the player data
err := result.Decode(&player)
if err != nil {
log.Println("Error decoding player:", err)
return player, err
}

fmt.Println("Updated Player -->", res)
return player, nil
}

// updateDoc := bson.M{"$set": bson.M{"team": newTeam, "title": newTitle}}

// updated, err := basketballdb.Collection.UpdateOne(context.TODO(), bson.D{})
}
type requestBody struct {
Name string `json:"name"`
IncrementPoint int `json:"incrementPoint"`
IncrementAssist int `json:"incrementAssist"`
}


func IncrementPlayerStats(player playerModel.Player, IncrementStats requestBody ) (playerModel.Player) {
fmt.Println("b4 pts::",player.Points);
fmt.Println("b4 ast::",player.Assists);
player.Points+=IncrementStats.IncrementPoint;
player.Assists+=IncrementStats.IncrementAssist;
fmt.Println("IncrementePLayerStats pts::",player.Points);
fmt.Println("IncrementePLayerStats ast::",player.Assists);
return player
}

func UpdateTeamPlayer(player playerModel.Player) (*mongo.UpdateResult) {
fmt.Println("recv pts::",player.Points);
fmt.Println("recv ast::",player.Assists);
update := bson.D{{"$set", bson.D{{"pts", player.Points},{"ast", player.Assists}}}}
updateRes,err :=basketballdb.Collection.UpdateByID(context.TODO(),player.ID,update)
if err != nil {
fmt.Println(err);
}
fmt.Println(updateRes);
return updateRes;
}
28 changes: 17 additions & 11 deletions src/api/basketball/model/player.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,23 @@ import (
)

// Player data structure (Acting as ORM ) for Basketball Players.

/*
Bson tags are essential for linking struct literals to the corresponding database fields.
They serve as a mapping mechanism between Go structs and the underlying database representation.
They provide a clear association between struct fields and their counterparts in the database. This mapping ensures proper serialization
and deserialization of data when interacting with databases.
*/
type Player struct {
Name string `json:"name,omitempty"`
Name string `json:"name,omitempty" bson:"name,omitempty"`
ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
ImageLink string `json:"imageLink,omitempty"`
Position string `json:"pos,omitempty"`
Branch string `json:"branch,omitempty"`
Year int `json:"year,omitempty"`
Age int `json:"age,omitempty"`
Instagram string `json:"instagram,omitempty"`
Minutes int `json:"min,omitempty"`
Rebounds int `json:"reb,omitempty"`
Assists int `json:"ast,omitempty"`
Points int `json:"pts,omitempty"`
ImageLink string `json:"imageLink,omitempty" bson:"imageLink,omitempty"`
Position string `json:"pos,omitempty" bson:"pos,omitempty"`
Branch string `json:"branch,omitempty" bson:"branch,omitempty"`
Year int `json:"year,omitempty" bson:"year,omitempty"`
Age int `json:"age,omitempty" bson:"age,omitempty"`
Instagram string `json:"instagram,omitempty" bson:"instagram,omitempty"`
Assists int `json:"ast,omitempty" bson:"ast,omitempty"`
Points int `json:"pts,omitempty" bson:"pts,omitempty"`
CollegeId string `json:"collegeId,omitempty" bson:"collegeId,omitempty"`
}
3 changes: 2 additions & 1 deletion src/api/basketball/routes/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ func Router() *mux.Router {

r.HandleFunc("/get-teamwise-players", controller.GetTeamWisePlayers).Methods("GET")
r.HandleFunc("/upload-player", controller.UploadTeamPlayer).Methods("POST")
r.HandleFunc("/update-player", controller.UpdateTeamPlayer).Methods("PUT")
r.HandleFunc("/update-player", controller.UpdateTeamPlayer).Methods("POST")
// r.HandleFunc("/get ")
return r
}
Loading