version 1
Build and Deploy / test-backend (push) Successful in 1m11s
Build and Deploy / lint-frontend (push) Successful in 21s
Build and Deploy / build-backend (push) Successful in 58s
Build and Deploy / deploy (push) Canceled after 0s
Build and Deploy / build-frontend (push) Canceled after 5m38s
Build and Deploy / test-backend (push) Successful in 1m11s
Build and Deploy / lint-frontend (push) Successful in 21s
Build and Deploy / build-backend (push) Successful in 58s
Build and Deploy / deploy (push) Canceled after 0s
Build and Deploy / build-frontend (push) Canceled after 5m38s
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/dusiburg/fancy-api/internal/model"
|
||||
"github.com/dusiburg/fancy-api/internal/provider/examples"
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type ExamplesService struct {
|
||||
provider examples.Provider
|
||||
redis *redis.Client
|
||||
}
|
||||
|
||||
func NewExamplesService(provider examples.Provider, r *redis.Client) *ExamplesService {
|
||||
return &ExamplesService{provider: provider, redis: r}
|
||||
}
|
||||
|
||||
func (s *ExamplesService) GenerateExamples(ctx context.Context, userID uuid.UUID, word string, lang model.Language) (*model.ExamplesResult, error) {
|
||||
key := examplesCacheKey(word, lang)
|
||||
ctx = WithUserID(ctx, userID)
|
||||
|
||||
val, err := s.redis.Get(ctx, key).Result()
|
||||
if err != nil && !errors.Is(err, redis.Nil) {
|
||||
log.Printf("getting key %q: %v", key, err)
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
var result model.ExamplesResult
|
||||
if err := json.Unmarshal([]byte(val), &result); err != nil {
|
||||
log.Printf("unmarshaling cached result for %q: %v", key, err)
|
||||
}
|
||||
result.Source = model.Cache
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
result, err := s.provider.GenerateExamples(ctx, word, lang)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("generating examples for %q [%s]: %w", word, lang, err)
|
||||
}
|
||||
result.Source = model.Provider
|
||||
generatedAt := time.Now().UTC()
|
||||
result.GeneratedAt = &generatedAt
|
||||
|
||||
if data, err := json.Marshal(result); err != nil {
|
||||
log.Printf("marshaling examples for cache %q: %v", key, err)
|
||||
} else if err := s.redis.Set(ctx, key, data, 0).Err(); err != nil {
|
||||
log.Printf("caching examples %q: %v", key, err)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func examplesCacheKey(word string, lang model.Language) string {
|
||||
sum := sha256.Sum256([]byte(word))
|
||||
return fmt.Sprintf("examples:%s:%s:%s", word, lang, hex.EncodeToString(sum[:]))
|
||||
}
|
||||
Reference in New Issue
Block a user