This commit is contained in:
saeid_01 2023-10-31 20:01:06 +03:30
parent 321381c8d7
commit 71cd11920b
12 changed files with 157 additions and 41 deletions

View File

@ -1,13 +1,15 @@
package handler_products
import (
"log"
"online-order/entity"
"online-order/repository/product"
"online-order/usecase/product"
)
func NewProductRouters(server *entity.Routers) {
productRepo := repository_product.NewProductClient(server.Database)
log.Printf("server: %v", server.ActiveBusiness)
productRepo := repository_product.NewProductClient(server.Database, &server.ActiveBusiness)
productService := service_product.NewProductService(productRepo)

View File

@ -0,0 +1,13 @@
package middlewares_log
import (
"log"
)
func SetOutputLogFile() {
logFile, _ := OpenFile("storage/logs/app.log")
if logFile != nil {
log.SetOutput(logFile)
}
}

View File

@ -0,0 +1,18 @@
package middlewares_log
import (
"fmt"
"os"
)
func OpenFile(path string) (*os.File, error) {
logFile, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
fmt.Println("Error in Open Log File:", err)
return nil, err
}
return logFile, nil
}

View File

@ -0,0 +1,26 @@
package middlewares_log
import (
"fmt"
"github.com/gin-gonic/gin"
"os"
"time"
)
func RequestLogger(logFile *os.File) gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
c.Next()
end := time.Now()
status := c.Writer.Status()
method := c.Request.Method
path := c.Request.URL.Path
host := c.Request.Host
latency := end.Sub(start)
logLine := fmt.Sprintf("%s | %3d | %s | %s | %s | %13v \n", end.Format("2006/01/02 - 15:04:05"), status, latency, method, host, path)
logFile.WriteString(logLine)
}
}

View File

@ -2,7 +2,6 @@ package middlewares
import (
"github.com/gin-gonic/gin"
"log"
"net/http"
"online-order/configs"
"online-order/domain"
@ -31,15 +30,20 @@ func DomainMiddleware(server *entity.Routers) gin.HandlerFunc {
// get domain from database
domainModel, err := domain.DomainService.GetByDomain(domainService, domainName)
log.Printf("domainModel name: %v", domainModel)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "domain not Found"})
c.Abort()
return
}
c.Set("domain", domainModel)
server.ActiveBusiness = entity.ActiveBusiness{
BusinessID: domainModel.BusinessID,
Domain: domainModel.Domain,
DomainID: domainModel.ID,
}
c.Set("activeBusiness", &server.ActiveBusiness)
c.Next()
}
}

52
api/router.go Normal file
View File

@ -0,0 +1,52 @@
package api
import (
"github.com/gin-gonic/gin"
logger "github.com/rs/zerolog/log"
swaggerfiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
handler_products "online-order/api/handlers/products"
"online-order/api/middlewares"
middlewares_log "online-order/api/middlewares/log"
docs "online-order/docs"
"online-order/ent"
"online-order/entity"
)
func Router(app *gin.Engine, db *ent.Client) {
docs.SwaggerInfo.BasePath = "/api/v1"
api_v1 := app.Group("api/v1")
api_restricted := app.Group("api/v1/in")
router_base := &entity.RouterBase{
Database: db,
OpenApp: api_v1,
}
router := &entity.Routers{
RouterBase: *router_base,
RestrictedApp: api_restricted,
}
middlewares_log.SetOutputLogFile()
logFile, _ := middlewares_log.OpenFile("storage/logs/request.log")
if logFile != nil {
api_v1.Use(middlewares_log.RequestLogger(logFile))
}
api_v1.Use(gin.Logger())
api_v1.Use(gin.Recovery())
api_v1.Use(middlewares.DomainMiddleware(router))
//middlewareController := middlewares.NewMiddlewareRouters(router)
//api_restricted.Use(middlewareController.JwAuthtMiddleware())
handler_products.NewProductRouters(router)
logger.Info().Msg("Server ready to go ...")
app.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerfiles.Handler,
ginSwagger.URL("http://localhost:9000/swagger/doc.json"),
ginSwagger.DefaultModelsExpandDepth(-1)))
}

View File

@ -0,0 +1,7 @@
package entity
type ActiveBusiness struct {
BusinessID int
Domain string
DomainID int
}

View File

@ -10,7 +10,12 @@ type RouterBase struct {
OpenApp *gin.RouterGroup
}
type RouterActiveBusiness struct {
ActiveBusiness ActiveBusiness
}
type Routers struct {
RouterBase
RouterActiveBusiness
RestrictedApp *gin.RouterGroup
}

34
main.go
View File

@ -5,15 +5,10 @@ import (
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
logger "github.com/rs/zerolog/log"
swaggerfiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
"log"
handler_products "online-order/api/handlers/products"
"online-order/api/middlewares"
"online-order/api"
"online-order/configs"
docs "online-order/docs"
"online-order/ent/migrate"
"online-order/entity"
)
// To load .env file
@ -61,32 +56,7 @@ func main() {
app := gin.Default()
docs.SwaggerInfo.BasePath = "/api/v1"
api_v1 := app.Group("api/v1")
api_restricted := app.Group("api/v1/in")
router_base := &entity.RouterBase{
Database: db,
OpenApp: api_v1,
}
router := &entity.Routers{
RouterBase: *router_base,
RestrictedApp: api_restricted,
}
api_v1.Use(middlewares.DomainMiddleware(router))
//middlewareController := middlewares.NewMiddlewareRouters(router)
//api_restricted.Use(middlewareController.JwAuthtMiddleware())
handler_products.NewProductRouters(router)
logger.Info().Msg("Server ready to go ...")
app.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerfiles.Handler,
ginSwagger.URL("http://localhost:9000/swagger/doc.json"),
ginSwagger.DefaultModelsExpandDepth(-1)))
api.Router(app, db)
app.Run(":" + conf.ServerPort)
}

View File

@ -89,6 +89,7 @@ func (c *DomainClient) GetByDomain(d string) (*entity.DomainDisplay, error) {
if len(resp) > 0 {
p.ID = resp[0].ID
p.Domain = resp[0].Domain
p.BusinessID = *resp[0].BusinessID
p.Status = resp[0].Status
p.CreatedAt = resp[0].CreatedAt
p.UpdatedAt = resp[0].UpdatedAt

View File

@ -9,14 +9,26 @@ import (
type ProductClient struct {
client *ent.Client
activeBusiness *entity.ActiveBusiness
}
func NewProductClient(client *ent.Client) *ProductClient {
func NewProductClient(client *ent.Client, activeBusiness *entity.ActiveBusiness) *ProductClient {
return &ProductClient{
client: client,
activeBusiness: activeBusiness,
}
}
//type ProductClient struct {
// client *ent.Client
//}
//
//func NewProductClient(client *ent.Client) *ProductClient {
// return &ProductClient{
// client: client,
// }
//}
// List all products
func (c *ProductClient) List() ([]*entity.ProductDisplay, error) {
var u []*entity.ProductDisplay
@ -24,6 +36,7 @@ func (c *ProductClient) List() ([]*entity.ProductDisplay, error) {
err := c.client.Product.
Query().
Where(product.BusinessID(c.activeBusiness.BusinessID)).
Select(product.FieldID, product.FieldName, product.FieldDescription, product.FieldOriginalPrice, product.FieldPrice, product.FieldQuantity, product.FieldStatus, product.FieldCreatedAt, product.FieldUpdatedAt).
Scan(ctx, &u)
@ -41,6 +54,7 @@ func (c *ProductClient) Create(p *entity.ProductCreateUpdate) error {
resp, err := c.client.Product.
Create().
SetName(p.Name).
SetBusinessID(c.activeBusiness.BusinessID).
SetNillableDescription(p.Description).
SetPrice(p.Price).
SetOriginalPrice(p.OriginalPrice).
@ -64,6 +78,7 @@ func (c *ProductClient) GetByID(id int) (*entity.ProductDisplay, error) {
resp := c.client.Product.
Query().
Where(product.BusinessID(c.activeBusiness.BusinessID)).
Where(product.ID(id)).
AllX(ctx)
@ -106,7 +121,8 @@ func (c *ProductClient) Update(p *entity.ProductCreateUpdate) error {
func (c *ProductClient) Delete(id int) error {
ctx := context.Background()
err := c.client.Product.DeleteOneID(id).
err := c.client.Product.
DeleteOneID(id).
Exec(ctx)
return err
}
@ -118,6 +134,7 @@ func (c *ProductClient) SearchProduct(identifier string) (*entity.ProductDisplay
resp := c.client.Product.
Query().
Where(product.BusinessID(c.activeBusiness.BusinessID)).
Where(
product.NameContains(identifier),
).

1
storage/logs/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
*.log