package controllers
import (
config "project_name/config"
models "project_name/models"
"context"
"log"
"math"
"strconv"
"time"
"github.com/gofiber/fiber/v2"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo/options"
)
func GetAllUser(c *fiber.Ctx) error {
userCollection := config.MI.DB.Collection("user")
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
var user []models.User
filter := bson.M{}
findOptions := options.Find()
page, _ := strconv.Atoi(c.Query("page", "1"))
limitVal, _ := strconv.Atoi(c.Query("limit", "10"))
var limit int64 = int64(limitVal)
total, _ := userCollection.CountDocuments(ctx, filter)
findOptions.SetSkip((int64(page) - 1) * limit)
findOptions.SetLimit(limit)
cursor, err := userCollection.Find(ctx, filter, findOptions)
defer cursor.Close(ctx)
if err != nil {
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{
"success": false,
"message": "user Not found",
"error": err,
})
}
for cursor.Next(ctx) {
var User models.User
cursor.Decode(&User)
user = append(user, User)
}
last := math.Ceil(float64(total / limit))
if last < 1 && total > 0 {
last = 1
}
return c.Status(fiber.StatusOK).JSON(fiber.Map{
"data": user,
"total": total,
"page": page,
"last_page": last,
"limit": limit,
})
}
func AddUser(c *fiber.Ctx) error {
userCollection := config.MI.DB.Collection("user")
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
User := new(models.User)
if err := c.BodyParser(User); err != nil {
log.Println(err)
return c.Status(400).JSON(fiber.Map{
"success": false,
"message": "Failed to parse body",
"error": err,
})
}
result, err := userCollection.InsertOne(ctx, User)
if err != nil {
return c.Status(500).JSON(fiber.Map{
"success": false,
"message": "User failed to insert",
"error": err,
})
}
return c.Status(fiber.StatusCreated).JSON(fiber.Map{
"data": result,
"success": true,
"message": "User inserted successfully",
})
}