Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add handler-cover and tests #29

Merged
merged 4 commits into from
Mar 8, 2025
Merged

add handler-cover and tests #29

merged 4 commits into from
Mar 8, 2025

Conversation

nik-mLb
Copy link
Collaborator

@nik-mLb nik-mLb commented Mar 7, 2025

No description provided.

cover.html Outdated
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это надо убрать из ПРа, т.к. этот файл можно будет командой из Makefile сгенерить

@@ -22,10 +26,19 @@ type BriefProduct struct {
}

func ConvertToBriefProduct(product *Product) BriefProduct{
coverPath := filepath.Join("./media", fmt.Sprintf("product-%s", product.ID), "cover.jpeg")
Copy link
Collaborator

@Benzogang-Tape Benzogang-Tape Mar 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"cover.jpg" и "./media" вынеси в константу

const (
    coverName = "cover.jpg"
    mediaPath = "./media"
)

@@ -22,10 +26,19 @@ type BriefProduct struct {
}

func ConvertToBriefProduct(product *Product) BriefProduct{
coverPath := filepath.Join("./media", fmt.Sprintf("product-%s", product.ID), "cover.jpeg")

imageURL := fmt.Sprintf("media/product-%s/cover.jpeg", product.ID)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В URL не нужно окончание .jpeg
Давай тут тоже через path.Join сделаем


if _, err := os.Stat(coverPath); os.IsNotExist(err) {
h.log.Warnf("Cover not found for product (ID: %d): %v", id, err)
http.Error(w, "Обложка не найдена", http.StatusNotFound)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Давай всё же на английском всё

)

const (
mediaFolder = "./media"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я выше писал про константы, в дальнейшем это у нас будет вынесено в конфиг, но пока можно ограничиться константами, главное в одном месте их объяви, думаю можно в models/product.go

)

//go:generate mockgen -source=product.go -destination=../repository/mocks/product_repo_mock.go package=mocks IProductRepo
type IProductRepo interface {
GetAllProducts(ctx context.Context) ([]*models.Product, error)
GetProductByID(ctx context.Context, id int) (*models.Product, error)
GetCoverPathProduct(ctx context.Context, id int) string
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Переименуй в GetProductCoverPath

Comment on lines 86 to 92
coverPath := filepath.Join("./media", fmt.Sprintf("product-%d", id), "cover.jpeg")

if _, err := os.Stat(coverPath); os.IsNotExist(err) {
coverPath = filepath.Join("./media", "product-default", "cover.jpeg")
}

return coverPath
Copy link
Collaborator

@Benzogang-Tape Benzogang-Tape Mar 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Давай эту логику вынесем в отдельную функцию в файл models/product.go

А тут будет что-то типо

storagePath := models.GetProductCoverPath(id)

if _, err := os.Stat(storagePath); os.IsNotExist(err) {
	return nil, fmt.Errorf("cover image not found")
}

return os.ReadFile(storagePath)

(Как пример)

Соответственно в transport/product.go логика чуть поменяется

Comment on lines 99 to 111
if _, err := os.Stat(coverPath); os.IsNotExist(err) {
h.log.Warnf("Cover not found for product (ID: %d): %v", id, err)
http.Error(w, "Обложка не найдена", http.StatusNotFound)
return
}

file, err := os.Open(coverPath)
if err != nil {
h.log.Errorf("Failed to open cover file (ID: %d): %v", id, err)
http.Error(w, "Ошибка при открытии файла", http.StatusInternalServerError)
return
}
defer file.Close()
Copy link
Collaborator

@Benzogang-Tape Benzogang-Tape Mar 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В связи с тем, о чём написал в комменте к методу репозитория этой логики здесь не будет

Copy link
Collaborator

@Benzogang-Tape Benzogang-Tape left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Напиши в тг как поправишь

http.Error(w, "Failed to encode", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(productJson)
}

func (h *ProductHandler) GetCoverProduct(w http.ResponseWriter, r *http.Request){
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут тоже переименуй пж в GetProductCover

// Копируем содержимое файла в ответ
if _, err := w.Write(fileData); err != nil {
h.log.Errorf("Failed to send cover file (ID: %d): %v", id, err)
http.Error(w, "Ошибка при отправке файла", http.StatusInternalServerError)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут на ингише

@nik-mLb nik-mLb merged commit c00a27f into develop Mar 8, 2025
@nik-mLb nik-mLb deleted the feature/cover-handler branch March 8, 2025 09:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants