online-order/repository/product/product.go
2023-10-28 01:42:56 +03:30

143 lines
3.0 KiB
Go

package repository_product
import (
"context"
"online-order/ent"
"online-order/ent/product"
"online-order/entity"
)
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
ctx := context.Background()
err := c.client.Product.
Query().
Select(product.FieldID, product.FieldName, product.FieldDescription, product.FieldOriginalPrice, product.FieldPrice, product.FieldQuantity, product.FieldStatus, product.FieldCreatedAt, product.FieldUpdatedAt).
Scan(ctx, &u)
if err != nil {
return nil, err
}
return u, nil
}
// Create a product
func (c *ProductClient) Create(p *entity.ProductCreateUpdate) error {
ctx := context.Background()
resp, err := c.client.Product.
Create().
SetName(p.Name).
SetNillableDescription(p.Description).
SetPrice(p.Price).
SetOriginalPrice(p.OriginalPrice).
SetQuantity(p.Quantity).
SetStatus(p.Status).
Save(ctx)
if err != nil {
return err
}
p.ID = resp.ID
p.CreatedAt = resp.CreatedAt
p.UpdatedAt = resp.UpdatedAt
return nil
}
func (c *ProductClient) GetByID(id int) (*entity.ProductDisplay, error) {
var p entity.ProductDisplay
ctx := context.Background()
resp := c.client.Product.
Query().
Where(product.ID(id)).
AllX(ctx)
if len(resp) > 0 {
p.ID = resp[0].ID
p.Name = resp[0].Name
p.Description = resp[0].Description
p.Status = resp[0].Status
p.Quantity = resp[0].Quantity
p.Price = resp[0].Price
p.OriginalPrice = resp[0].OriginalPrice
p.CreatedAt = resp[0].CreatedAt
p.UpdatedAt = resp[0].UpdatedAt
} else {
return nil, entity.ErrNotFound
}
return &p, nil
}
// Update product information, except password
func (c *ProductClient) Update(p *entity.ProductCreateUpdate) error {
ctx := context.Background()
_, err := c.client.Product.UpdateOneID(p.ID).
SetName(p.Name).
SetDescription(p.Name).
SetPrice(p.Price).
SetOriginalPrice(p.OriginalPrice).
SetQuantity(p.Quantity).
SetStatus(p.Status).
Save(ctx)
if err != nil {
return err
}
return nil
}
// Update user information, except password
func (c *ProductClient) Delete(id int) error {
ctx := context.Background()
err := c.client.Product.DeleteOneID(id).
Exec(ctx)
return err
}
// Search a user information by email or username
func (c *ProductClient) SearchProduct(identifier string) (*entity.ProductDisplay, error) {
var p entity.ProductDisplay
ctx := context.Background()
resp := c.client.Product.
Query().
Where(
product.NameContains(identifier),
).
AllX(ctx)
if len(resp) > 0 {
p.ID = resp[0].ID
p.Name = resp[0].Name
p.Description = resp[0].Description
p.Status = resp[0].Status
p.Quantity = resp[0].Quantity
p.Price = resp[0].Price
p.OriginalPrice = resp[0].OriginalPrice
p.CreatedAt = resp[0].CreatedAt
p.UpdatedAt = resp[0].UpdatedAt
} else {
return nil, entity.ErrNotFound
}
return &p, nil
}