Commit 497b1f80 authored by Ai-Sasit's avatar Ai-Sasit

ฉบับปรับปรุง

parent ecfba286
...@@ -16,7 +16,8 @@ func ConnectDB() *mongo.Client { ...@@ -16,7 +16,8 @@ func ConnectDB() *mongo.Client {
log.Fatal("err") log.Fatal("err")
} }
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = client.Connect(ctx) err = client.Connect(ctx)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
...@@ -37,6 +38,6 @@ var DB *mongo.Client = ConnectDB() ...@@ -37,6 +38,6 @@ var DB *mongo.Client = ConnectDB()
// getting database collections // getting database collections
func GetCollection(client *mongo.Client, collectionName string) *mongo.Collection { func GetCollection(client *mongo.Client, collectionName string) *mongo.Collection {
collection := client.Database("golangAPI").Collection(collectionName) collection := client.Database("Esan-Shabu").Collection(collectionName)
return collection return collection
} }
package controllers package controllers
import ( import (
"Esan-Shabu/configs"
"Esan-Shabu/models"
"Esan-Shabu/responses"
"context" "context"
"fiber-mongo-api/configs"
"fiber-mongo-api/models"
"fiber-mongo-api/responses"
"net/http" "net/http"
"time" "time"
...@@ -23,12 +23,12 @@ func CreateCategory(c *fiber.Ctx) error { ...@@ -23,12 +23,12 @@ func CreateCategory(c *fiber.Ctx) error {
//validate the request body //validate the request body
if err := c.BodyParser(&category); err != nil { if err := c.BodyParser(&category); err != nil {
return c.Status(http.StatusBadRequest).JSON(responses.CategoryResponse{Status: http.StatusBadRequest, Message: "error", Data: &fiber.Map{"data": err.Error()}}) return c.Status(http.StatusBadRequest).JSON(responses.CategoryResponse{Status: http.StatusBadRequest, Message: err.Error() })
} }
//use the validator library to validate required fields //use the validator library to validate required fields
if validationErr := validate.Struct(&category); validationErr != nil { if validationErr := validate.Struct(&category); validationErr != nil {
return c.Status(http.StatusBadRequest).JSON(responses.CategoryResponse{Status: http.StatusBadRequest, Message: "error", Data: &fiber.Map{"data": validationErr.Error()}}) return c.Status(http.StatusBadRequest).JSON(responses.CategoryResponse{Status: http.StatusBadRequest, Message: validationErr.Error() })
} }
newCategory := models.Category{ newCategory := models.Category{
...@@ -37,13 +37,13 @@ func CreateCategory(c *fiber.Ctx) error { ...@@ -37,13 +37,13 @@ func CreateCategory(c *fiber.Ctx) error {
result, err := categoryCollection.InsertOne(ctx, newCategory) result, err := categoryCollection.InsertOne(ctx, newCategory)
if err != nil { if err != nil {
return c.Status(http.StatusInternalServerError).JSON(responses.CategoryResponse{Status: http.StatusInternalServerError, Message: "error", Data: &fiber.Map{"data": err.Error()}}) return c.Status(http.StatusInternalServerError).JSON(responses.CategoryResponse{Status: http.StatusInternalServerError, Message: err.Error() })
} }
return c.Status(http.StatusCreated).JSON(responses.CategoryResponse{Status: http.StatusCreated, Message: "success", Data: &fiber.Map{"data": result}}) return c.Status(http.StatusCreated).JSON(responses.CategoryResponse{Status: http.StatusCreated, Message: "success", Data: result})
} }
func GetACategory(c *fiber.Ctx) error { func GetCategoryById(c *fiber.Ctx) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
categoryId := c.Params("categoryId") categoryId := c.Params("categoryId")
var category models.Category var category models.Category
...@@ -53,10 +53,10 @@ func GetACategory(c *fiber.Ctx) error { ...@@ -53,10 +53,10 @@ func GetACategory(c *fiber.Ctx) error {
err := categoryCollection.FindOne(ctx, bson.M{"id": objId}).Decode(&category) err := categoryCollection.FindOne(ctx, bson.M{"id": objId}).Decode(&category)
if err != nil { if err != nil {
return c.Status(http.StatusInternalServerError).JSON(responses.CategoryResponse{Status: http.StatusInternalServerError, Message: "error", Data: &fiber.Map{"data": err.Error()}}) return c.Status(http.StatusInternalServerError).JSON(responses.CategoryResponse{Status: http.StatusInternalServerError, Message: err.Error()})
} }
return c.Status(http.StatusOK).JSON(responses.CategoryResponse{Status: http.StatusOK, Message: "success", Data: &fiber.Map{"data": category}}) return c.Status(http.StatusOK).JSON(responses.CategoryResponse{Status: http.StatusOK, Message: "success", Data: category})
} }
func EditACategory(c *fiber.Ctx) error { func EditACategory(c *fiber.Ctx) error {
...@@ -69,32 +69,34 @@ func EditACategory(c *fiber.Ctx) error { ...@@ -69,32 +69,34 @@ func EditACategory(c *fiber.Ctx) error {
//validate the request body //validate the request body
if err := c.BodyParser(&category); err != nil { if err := c.BodyParser(&category); err != nil {
return c.Status(http.StatusBadRequest).JSON(responses.CategoryResponse{Status: http.StatusBadRequest, Message: "error", Data: &fiber.Map{"data": err.Error()}}) return c.Status(http.StatusBadRequest).JSON(responses.CategoryResponse{Status: http.StatusBadRequest, Message: err.Error()})
} }
//use the validator library to validate required fields //use the validator library to validate required fields
if validationErr := validate.Struct(&category); validationErr != nil { if validationErr := validate.Struct(&category); validationErr != nil {
return c.Status(http.StatusBadRequest).JSON(responses.CategoryResponse{Status: http.StatusBadRequest, Message: "error", Data: &fiber.Map{"data": validationErr.Error()}}) return c.Status(http.StatusBadRequest).JSON(responses.CategoryResponse{Status: http.StatusBadRequest, Message: validationErr.Error()})
} }
update := bson.M{"name": category.Name} update := models.Category{
Name: category.Name,
}
result, err := categoryCollection.UpdateOne(ctx, bson.M{"id": objId}, bson.M{"$set": update}) result, err := categoryCollection.UpdateOne(ctx, bson.M{"_id": objId}, bson.M{"$set": update})
if err != nil { if err != nil {
return c.Status(http.StatusInternalServerError).JSON(responses.CategoryResponse{Status: http.StatusInternalServerError, Message: "error", Data: &fiber.Map{"data": err.Error()}}) return c.Status(http.StatusInternalServerError).JSON(responses.CategoryResponse{Status: http.StatusInternalServerError, Message: err.Error()})
} }
//get updated user details //get updated user details
var updatedCategory models.Category var updatedCategory models.Category
if result.MatchedCount == 1 { if result.MatchedCount == 1 {
err := categoryCollection.FindOne(ctx, bson.M{"id": objId}).Decode(&updatedCategory) err := categoryCollection.FindOne(ctx, bson.M{"_id": objId}).Decode(&updatedCategory)
if err != nil { if err != nil {
return c.Status(http.StatusInternalServerError).JSON(responses.CategoryResponse{Status: http.StatusInternalServerError, Message: "error", Data: &fiber.Map{"data": err.Error()}}) return c.Status(http.StatusInternalServerError).JSON(responses.CategoryResponse{Status: http.StatusInternalServerError, Message: err.Error()})
} }
} }
return c.Status(http.StatusOK).JSON(responses.CategoryResponse{Status: http.StatusOK, Message: "success", Data: &fiber.Map{"data": updatedCategory}}) return c.Status(http.StatusOK).JSON(responses.CategoryResponse{Status: http.StatusOK, Message: "success", Data: updatedCategory})
} }
func DeleteACategory(c *fiber.Ctx) error { func DeleteACategory(c *fiber.Ctx) error {
...@@ -104,45 +106,38 @@ func DeleteACategory(c *fiber.Ctx) error { ...@@ -104,45 +106,38 @@ func DeleteACategory(c *fiber.Ctx) error {
objId, _ := primitive.ObjectIDFromHex(categoryId) objId, _ := primitive.ObjectIDFromHex(categoryId)
result, err := categoryCollection.DeleteOne(ctx, bson.M{"id": objId}) result, err := categoryCollection.DeleteOne(ctx, bson.M{"_id": objId})
if err != nil { if err != nil {
return c.Status(http.StatusInternalServerError).JSON(responses.CategoryResponse{Status: http.StatusInternalServerError, Message: "error", Data: &fiber.Map{"data": err.Error()}}) return c.Status(http.StatusInternalServerError).JSON(responses.CategoryResponse{Status: http.StatusInternalServerError, Message: err.Error()})
} }
if result.DeletedCount < 1 { if result.DeletedCount < 1 {
return c.Status(http.StatusNotFound).JSON( return c.Status(http.StatusNotFound).JSON(
responses.CategoryResponse{Status: http.StatusNotFound, Message: "error", Data: &fiber.Map{"data": "Category with specified ID not found!"}}, responses.CategoryResponse{Status: http.StatusNotFound, Message: "Category with specified ID not found!"},
) )
} }
return c.Status(http.StatusOK).JSON( return c.Status(http.StatusOK).JSON(
responses.CategoryResponse{Status: http.StatusOK, Message: "success", Data: &fiber.Map{"data": "Category successfully deleted!"}}, responses.CategoryResponse{Status: http.StatusOK, Message: "Category successfully deleted!"},
) )
} }
func GetAllCategorys(c *fiber.Ctx) error { func GetAllCategories(c *fiber.Ctx) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
var categorys []models.Category var categories []models.Category
defer cancel() defer cancel()
results, err := categoryCollection.Find(ctx, bson.M{}) results, err := categoryCollection.Find(ctx, bson.M{})
if err != nil { if err != nil {
return c.Status(http.StatusInternalServerError).JSON(responses.CategoryResponse{Status: http.StatusInternalServerError, Message: "error", Data: &fiber.Map{"data": err.Error()}}) return c.Status(http.StatusInternalServerError).JSON(responses.CategoryResponse{Status: http.StatusInternalServerError, Message: err.Error()})
} }
//reading from the db in an optimal way if err = results.All(ctx, &categories); err != nil {
defer results.Close(ctx) return c.Status(http.StatusInternalServerError).JSON(responses.CategoryResponse{Status: http.StatusInternalServerError, Message: err.Error()})
for results.Next(ctx) {
var singleUser models.Category
if err = results.Decode(&singleUser); err != nil {
return c.Status(http.StatusInternalServerError).JSON(responses.CategoryResponse{Status: http.StatusInternalServerError, Message: "error", Data: &fiber.Map{"data": err.Error()}})
}
categorys = append(categorys, singleUser)
} }
return c.Status(http.StatusOK).JSON( return c.Status(http.StatusOK).JSON(
responses.CategoryResponse{Status: http.StatusOK, Message: "success", Data: &fiber.Map{"data": categorys}}, responses.CategoryResponse{Status: http.StatusOK, Message: "success", Data: categories},
) )
} }
package controllers package controllers
import ( import (
"Esan-Shabu/configs"
"Esan-Shabu/models"
"Esan-Shabu/responses"
"context" "context"
"fiber-mongo-api/configs"
"fiber-mongo-api/models"
"fiber-mongo-api/responses"
"net/http" "net/http"
"time" "time"
......
package controllers package controllers
import ( import (
"Esan-Shabu/configs"
"Esan-Shabu/models"
"Esan-Shabu/responses"
"context" "context"
"fiber-mongo-api/configs"
"fiber-mongo-api/models"
"fiber-mongo-api/responses"
"net/http" "net/http"
"time" "time"
......
package controllers package controllers
import ( import (
"Esan-Shabu/configs"
"Esan-Shabu/models"
"Esan-Shabu/responses"
"context" "context"
"fiber-mongo-api/configs"
"fiber-mongo-api/models"
"fiber-mongo-api/responses"
"net/http" "net/http"
"time" "time"
......
module fiber-mongo-api module Esan-Shabu
go 1.17 go 1.17
......
package main package main
import ( import (
"fiber-mongo-api/routes" //add this "Esan-Shabu/routes" //add this
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors" "github.com/gofiber/fiber/v2/middleware/cors"
......
package responses package responses
import "github.com/gofiber/fiber/v2"
type CategoryResponse struct { type CategoryResponse struct {
Status int `json:"status"` Status int `json:"status"`
Message string `json:"message"` Message string `json:"message"`
Data *fiber.Map `json:"data"` Data interface{} `json:"data"`
} }
package routes package routes
import ( import (
"fiber-mongo-api/controllers" "Esan-Shabu/controllers"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
) )
func CategoryRoute(app *fiber.App) { func CategoryRoute(app *fiber.App) {
app.Post("/category", controllers.CreateCategory) app.Post("/category", controllers.CreateCategory)
app.Get("/category/:categoryId", controllers.GetACategory) app.Get("/category/:categoryId", controllers.GetCategoryById)
app.Put("/category/:categoryId", controllers.EditACategory) app.Put("/category/:categoryId", controllers.EditACategory)
app.Delete("/category/:categoryId", controllers.DeleteACategory) app.Delete("/category/:categoryId", controllers.DeleteACategory)
app.Get("/categorys", controllers.GetAllCategorys) app.Get("/categories", controllers.GetAllCategories)
} }
package routes package routes
import ( import (
"fiber-mongo-api/controllers" "Esan-Shabu/controllers"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
) )
......
package routes package routes
import ( import (
"fiber-mongo-api/controllers" "Esan-Shabu/controllers"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
) )
......
package routes package routes
import ( import (
"fiber-mongo-api/controllers" "Esan-Shabu/controllers"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
) )
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment