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

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

parent ecfba286
......@@ -16,7 +16,8 @@ func ConnectDB() *mongo.Client {
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)
if err != nil {
log.Fatal(err)
......@@ -37,6 +38,6 @@ var DB *mongo.Client = ConnectDB()
// getting database collections
func GetCollection(client *mongo.Client, collectionName string) *mongo.Collection {
collection := client.Database("golangAPI").Collection(collectionName)
collection := client.Database("Esan-Shabu").Collection(collectionName)
return collection
}
package controllers
import (
"Esan-Shabu/configs"
"Esan-Shabu/models"
"Esan-Shabu/responses"
"context"
"fiber-mongo-api/configs"
"fiber-mongo-api/models"
"fiber-mongo-api/responses"
"net/http"
"time"
......@@ -23,12 +23,12 @@ func CreateCategory(c *fiber.Ctx) error {
//validate the request body
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
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{
......@@ -37,13 +37,13 @@ func CreateCategory(c *fiber.Ctx) error {
result, err := categoryCollection.InsertOne(ctx, newCategory)
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)
categoryId := c.Params("categoryId")
var category models.Category
......@@ -53,10 +53,10 @@ func GetACategory(c *fiber.Ctx) error {
err := categoryCollection.FindOne(ctx, bson.M{"id": objId}).Decode(&category)
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 {
......@@ -69,32 +69,34 @@ func EditACategory(c *fiber.Ctx) error {
//validate the request body
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
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 {
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
var updatedCategory models.Category
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 {
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 {
......@@ -104,45 +106,38 @@ func DeleteACategory(c *fiber.Ctx) error {
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 {
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 {
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(
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)
var categorys []models.Category
var categories []models.Category
defer cancel()
results, err := categoryCollection.Find(ctx, bson.M{})
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
defer results.Close(ctx)
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)
if err = results.All(ctx, &categories); err != nil {
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": categorys}},
responses.CategoryResponse{Status: http.StatusOK, Message: "success", Data: categories},
)
}
package controllers
import (
"Esan-Shabu/configs"
"Esan-Shabu/models"
"Esan-Shabu/responses"
"context"
"fiber-mongo-api/configs"
"fiber-mongo-api/models"
"fiber-mongo-api/responses"
"net/http"
"time"
......
package controllers
import (
"Esan-Shabu/configs"
"Esan-Shabu/models"
"Esan-Shabu/responses"
"context"
"fiber-mongo-api/configs"
"fiber-mongo-api/models"
"fiber-mongo-api/responses"
"net/http"
"time"
......
package controllers
import (
"Esan-Shabu/configs"
"Esan-Shabu/models"
"Esan-Shabu/responses"
"context"
"fiber-mongo-api/configs"
"fiber-mongo-api/models"
"fiber-mongo-api/responses"
"net/http"
"time"
......
module fiber-mongo-api
module Esan-Shabu
go 1.17
......
package main
import (
"fiber-mongo-api/routes" //add this
"Esan-Shabu/routes" //add this
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
......
package responses
import "github.com/gofiber/fiber/v2"
type CategoryResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data *fiber.Map `json:"data"`
Data interface{} `json:"data"`
}
package routes
import (
"fiber-mongo-api/controllers"
"Esan-Shabu/controllers"
"github.com/gofiber/fiber/v2"
)
func CategoryRoute(app *fiber.App) {
app.Post("/category", controllers.CreateCategory)
app.Get("/category/:categoryId", controllers.GetACategory)
app.Get("/category/:categoryId", controllers.GetCategoryById)
app.Put("/category/:categoryId", controllers.EditACategory)
app.Delete("/category/:categoryId", controllers.DeleteACategory)
app.Get("/categorys", controllers.GetAllCategorys)
app.Get("/categories", controllers.GetAllCategories)
}
package routes
import (
"fiber-mongo-api/controllers"
"Esan-Shabu/controllers"
"github.com/gofiber/fiber/v2"
)
......
package routes
import (
"fiber-mongo-api/controllers"
"Esan-Shabu/controllers"
"github.com/gofiber/fiber/v2"
)
......
package routes
import (
"fiber-mongo-api/controllers"
"Esan-Shabu/controllers"
"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