aides-repo-api/internal/controllers/taskcontroller/upload.go
Maxim Slipenko 939f14eb86
Some checks failed
Format and Lint / format-check (push) Failing after 4s
Format and Lint / test (push) Successful in 53s
fix: reduce memory usage
2025-01-08 15:30:48 +03:00

106 lines
2.7 KiB
Go

package taskcontroller
import (
"errors"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/go-chi/render"
commonErrors "code.aides.space/aides-infra/aides-repo-api/internal/common/errors"
"code.aides.space/aides-infra/aides-repo-api/internal/logger"
"code.aides.space/aides-infra/aides-repo-api/internal/services/taskservice"
)
type TaskUploadResponse struct {
TaskID string `json:"taskID"`
StatusText string `json:"status"`
}
func (rd *TaskUploadResponse) Render(w http.ResponseWriter, r *http.Request) error {
return nil
}
// Upload handles file uploads for a specific task.
//
// @Summary Upload files to a task
// @Description Upload multiple files associated with a specific task ID. Each file must be less than 10MB.
// @Tags tasks
// @Security ApiKeyAuth
// @Accept multipart/form-data
// @Produce json
// @Param taskID path string true "Task ID"
// @Param files formData file true "Files to upload"
// @Success 200 {object} TaskUploadResponse "Successful file upload"
// @Failure 400 {object} errors.ErrResponse "Bad Request or File too large"
// @Failure 500 {object} errors.ErrResponse "Internal Server Error"
// @Router /tasks/{taskID}/upload [post]
func (c *TaskController) Upload(w http.ResponseWriter, r *http.Request) {
taskID := chi.URLParam(r, "taskID")
if taskID == "" {
render.Render(w, r, &commonErrors.ErrResponse{
HTTPStatusCode: http.StatusBadRequest,
StatusText: "taskID is required",
})
return
}
err := r.ParseMultipartForm(10 << 20)
if err != nil {
render.Render(w, r, &commonErrors.ErrResponse{
HTTPStatusCode: http.StatusBadRequest,
StatusText: "Bad Request",
})
return
}
files := r.MultipartForm.File["files"]
for _, fileHeader := range files {
if fileHeader.Size > (4096 << 20) {
render.Render(w, r, &commonErrors.ErrResponse{
HTTPStatusCode: http.StatusBadRequest,
StatusText: "File too large",
})
return
}
}
err = c.taskService.Upload(&taskservice.TaskUploadInput{
TaskID: taskID,
Files: files,
})
if err != nil {
log := logger.GetLogger()
log.Error("Error while upload task", map[string]interface{}{
"err": err,
})
var e *taskservice.TooOldError
if errors.As(err, &e) {
render.Render(w, r, &commonErrors.ErrResponse{
HTTPStatusCode: http.StatusBadRequest,
StatusText: err.Error(),
Err: err,
})
return
}
render.Render(w, r, &commonErrors.ErrResponse{
HTTPStatusCode: http.StatusInternalServerError,
StatusText: "Internal Server Error",
Err: err,
})
return
}
response := TaskUploadResponse{
TaskID: taskID,
StatusText: "Success!",
}
if err := render.Render(w, r, &response); err != nil {
render.Render(w, r, commonErrors.ErrRender(err))
return
}
}