Files
b2b/app/repos/searchRepo/searchRepo.go
Daniel Goc b2acb8c922 storage
2026-04-01 13:30:54 +02:00

83 lines
2.0 KiB
Go

package searchrepo
import (
"bytes"
"fmt"
"io"
"net/http"
"git.ma-al.com/goc_daniel/b2b/app/config"
"git.ma-al.com/goc_daniel/b2b/app/model"
)
type SearchProxyResponse struct {
StatusCode int
Body []byte
}
type UISearchRepo interface {
Search(index string, body []byte) (*SearchProxyResponse, error)
GetIndexSettings(index string) (*SearchProxyResponse, error)
GetRoutes(langId uint) ([]model.Route, error)
}
type SearchRepo struct {
cfg *config.Config
}
func New() UISearchRepo {
return &SearchRepo{
cfg: config.Get(),
}
}
func (r *SearchRepo) Search(index string, body []byte) (*SearchProxyResponse, error) {
url := fmt.Sprintf("%s/indexes/%s/search", r.cfg.MeiliSearch.ServerURL, index)
return r.doRequest(http.MethodPost, url, body)
}
func (r *SearchRepo) GetIndexSettings(index string) (*SearchProxyResponse, error) {
url := fmt.Sprintf("%s/indexes/%s/settings", r.cfg.MeiliSearch.ServerURL, index)
return r.doRequest(http.MethodGet, url, nil)
}
func (r *SearchRepo) doRequest(method, url string, body []byte) (*SearchProxyResponse, error) {
var reqBody *bytes.Reader
if body != nil {
reqBody = bytes.NewReader(body)
} else {
reqBody = bytes.NewReader([]byte{})
}
req, err := http.NewRequest(method, url, reqBody)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
if r.cfg.MeiliSearch.ApiKey != "" {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", r.cfg.MeiliSearch.ApiKey))
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to reach meilisearch: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
return &SearchProxyResponse{
StatusCode: resp.StatusCode,
Body: respBody,
}, nil
}
func (r *SearchRepo) GetRoutes(langId uint) ([]model.Route, error) {
return nil, nil
}