Improve API

This commit is contained in:
2023-04-02 17:31:37 +03:00
parent bc61b916f9
commit 11a6171954
12 changed files with 260 additions and 25 deletions

View File

@@ -1,6 +1,8 @@
package rest
import (
"fmt"
"github.com/derfenix/webarchive/api/openapi"
"github.com/derfenix/webarchive/entity"
)
@@ -93,7 +95,7 @@ func StatusToRest(s entity.Status) openapi.Status {
}
}
func FormatFromRest(format []openapi.Format) []entity.Format {
func FormatFromRest(format []openapi.Format) ([]entity.Format, error) {
var formats []entity.Format
switch {
@@ -112,11 +114,14 @@ func FormatFromRest(format []openapi.Format) []entity.Format {
case openapi.FormatSingleFile:
formats[i] = entity.FormatSingleFile
default:
return nil, fmt.Errorf("invalid format value %s", format)
}
}
}
return formats
return formats, nil
}
func FormatToRest(format entity.Format) openapi.Format {

View File

@@ -41,7 +41,7 @@ func (s *Service) GetPage(ctx context.Context, params openapi.GetPageParams) (op
return &restPage, nil
}
func (s *Service) AddPage(ctx context.Context, req openapi.OptAddPageReq, params openapi.AddPageParams) (*openapi.Page, error) {
func (s *Service) AddPage(ctx context.Context, req openapi.OptAddPageReq, params openapi.AddPageParams) (openapi.AddPageRes, error) {
url := params.URL.Or(req.Value.URL)
description := params.Description.Or(req.Value.Description.Value)
@@ -60,19 +60,32 @@ func (s *Service) AddPage(ctx context.Context, req openapi.OptAddPageReq, params
url = params.URL.Value
}
page := entity.NewPage(url, description, FormatFromRest(formats)...)
if url == "" {
return &openapi.AddPageBadRequest{
Field: "url",
Error: "Value is required",
}, nil
}
domainFormats, err := FormatFromRest(formats)
if err != nil {
return &openapi.AddPageBadRequest{
Field: "formats",
Error: err.Error(),
}, nil
}
page := entity.NewPage(url, description, domainFormats...)
page.Status = entity.StatusProcessing
err := s.pages.Save(ctx, page)
if err != nil {
if err := s.pages.Save(ctx, page); err != nil {
return nil, fmt.Errorf("save page: %w", err)
}
s.ch <- page
res := PageToRest(page)
s.ch <- page
return &res, nil
}