-
Notifications
You must be signed in to change notification settings - Fork 24
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add: endpoint to fetch all stocks and handlong nil pointer exceptions
Signed-off-by: shivamsouravjha <[email protected]>
- Loading branch information
1 parent
17b311d
commit c67dd7e
Showing
6 changed files
with
235 additions
and
22 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
package controllers | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
"os" | ||
mongo_client "stockbackend/clients/mongo" | ||
"stockbackend/utils/helpers" | ||
"strconv" | ||
|
||
"github.com/gin-gonic/gin" | ||
"go.mongodb.org/mongo-driver/mongo/options" | ||
"go.uber.org/zap" | ||
"gopkg.in/mgo.v2/bson" | ||
) | ||
|
||
type StockControllerI interface { | ||
GetStocks(ctx *gin.Context) | ||
} | ||
|
||
type stockController struct{} | ||
|
||
var StockController StockControllerI = &stockController{} | ||
|
||
func (s *stockController) GetStocks(ctx *gin.Context) { | ||
// parse the reuqest for pag number and last fetcehd stock fo r pagination | ||
pageNumberStr := ctx.DefaultQuery("pageNumber", "1") | ||
pageNumber, err := strconv.Atoi(pageNumberStr) | ||
if err != nil || pageNumber < 1 { | ||
ctx.JSON(400, gin.H{"error": "Invalid page number"}) | ||
return | ||
} | ||
// fetch the stocks from the database | ||
collection := mongo_client.Client.Database(os.Getenv("DATABASE")).Collection(os.Getenv("COLLECTION")) | ||
|
||
//write a code that does the limit annd the page size for the stocks | ||
findOptions := options.Find() | ||
findOptions.SetLimit(10) | ||
findOptions.SetSkip(int64(10 * (pageNumber - 1))) | ||
findOptions.SetSort(bson.M{"rank": -1}) | ||
cursor, err := collection.Find(ctx, bson.M{}, findOptions) | ||
if err != nil { | ||
zap.L().Error("Error while fetching documents", zap.Error(err)) | ||
ctx.JSON(500, gin.H{"error": "Error while fetching stocks"}) | ||
return | ||
} | ||
defer cursor.Close(ctx) | ||
for cursor.Next(ctx) { | ||
var result bson.M | ||
err := cursor.Decode(&result) | ||
if err != nil { | ||
ctx.JSON(500, gin.H{"error": "Error while decoding stocks"}) | ||
return | ||
} | ||
stockDetail := make(map[string]interface{}) | ||
stockDetail["name"] = result["name"] | ||
stockDetail["marketCapValue"] = result["marketCap"] | ||
stockDetail["url"] = result["url"] | ||
stockDetail["marketCap"] = helpers.GetMarketCapCategory(fmt.Sprintf("%v", result["marketCap"])) | ||
stockDetail["stockRate"] = result["rank"] | ||
fmt.Println(result["fScore"], "fScore") | ||
stockDetail["fScore"] = result["fScore"] | ||
stockDataMarshal, err := json.Marshal(stockDetail) | ||
if err != nil { | ||
zap.L().Error("Error marshalling data", zap.Error(err)) | ||
continue | ||
} | ||
|
||
_, err = ctx.Writer.Write(append(stockDataMarshal, '\n')) // Send each stockDetail as JSON with a newline separator | ||
|
||
if err != nil { | ||
zap.L().Error("Error writing data", zap.Error(err)) | ||
break | ||
} | ||
ctx.Writer.Flush() // Flush each chunk immediately to the client | ||
} | ||
ctx.JSON(200, gin.H{"message": "Stocks are fetched"}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
package middleware | ||
|
||
import ( | ||
"net/http" | ||
"runtime/debug" | ||
|
||
"github.com/gin-gonic/gin" | ||
"go.uber.org/zap" | ||
) | ||
|
||
// RecoveryMiddleware catches panics and prevents the server from crashing | ||
func RecoveryMiddleware() gin.HandlerFunc { | ||
return func(ctx *gin.Context) { | ||
defer func() { | ||
if r := recover(); r != nil { | ||
// Log the panic and stack trace | ||
zap.L().Error("Panic recovered", zap.Any("panic", r), zap.String("stack", string(debug.Stack()))) | ||
// Respond with a 500 Internal Server Error | ||
ctx.JSON(http.StatusInternalServerError, gin.H{ | ||
"error": "Internal server error. Please try again later.", | ||
}) | ||
ctx.Abort() | ||
} | ||
}() | ||
// Continue to the next handler | ||
ctx.Next() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
package services | ||
|
||
import ( | ||
"context" | ||
"os" | ||
mongo_client "stockbackend/clients/mongo" | ||
"stockbackend/utils/helpers" | ||
|
||
"go.mongodb.org/mongo-driver/mongo/options" | ||
"go.uber.org/zap" | ||
"gopkg.in/mgo.v2/bson" | ||
) | ||
|
||
// write a function that travereses throguht al the documents of the mongo db | ||
// and updates the rank of the stock | ||
func UpdateRating() { | ||
collection := mongo_client.Client.Database(os.Getenv("DATABASE")).Collection(os.Getenv("COLLECTION")) | ||
findOptions := options.Find() | ||
cursor, err := collection.Find(context.Background(), bson.M{}, findOptions) | ||
if err != nil { | ||
zap.L().Error("Error while fetching documents", zap.Error(err)) | ||
} | ||
defer cursor.Close(context.Background()) | ||
var stockRate float64 | ||
for cursor.Next(context.Background()) { | ||
var result bson.M | ||
err := cursor.Decode(&result) | ||
if err != nil { | ||
zap.L().Error("Error while decoding document", zap.Error(err)) | ||
} | ||
stockRate = helpers.RateStock(result) | ||
fscore := helpers.GenerateFScore(result) | ||
_, err = collection.UpdateOne(context.Background(), bson.M{"_id": result["_id"]}, bson.M{"$set": bson.M{"rank": stockRate, "fScore": fscore}}) | ||
if err != nil { | ||
zap.L().Error("Error while updating document", zap.Error(err)) | ||
} | ||
zap.L().Info("Updated rank for stock", zap.Any("stock", result["name"]), zap.Any("rate", stockRate)) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters