73 lines
1.4 KiB
Go
73 lines
1.4 KiB
Go
|
package savewc
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"encoding/json"
|
||
|
"fmt"
|
||
|
"github.com/go-redis/redis/v8"
|
||
|
"github.com/themakers/hlog"
|
||
|
"penahub.gitlab.yandexcloud.net/backend/quiz/common.git/model"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
type DepsForClient struct {
|
||
|
WorkerSendClientCh chan model.Answer
|
||
|
Redis *redis.Client
|
||
|
}
|
||
|
|
||
|
type SaveForClient struct {
|
||
|
deps DepsForClient
|
||
|
errChan chan<- error
|
||
|
logger hlog.Logger
|
||
|
}
|
||
|
|
||
|
func NewSaveClientWorker(deps DepsForClient, errChan chan<- error, logger hlog.Logger) *SaveForClient {
|
||
|
return &SaveForClient{
|
||
|
deps: deps,
|
||
|
errChan: errChan,
|
||
|
logger: logger,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (w *SaveForClient) Start(ctx context.Context) {
|
||
|
|
||
|
for {
|
||
|
select {
|
||
|
case answer, ok := <-w.deps.WorkerSendClientCh:
|
||
|
if !ok {
|
||
|
return
|
||
|
}
|
||
|
fmt.Println("SAVECLINT")
|
||
|
err := w.saveAnswer(ctx, answer)
|
||
|
if err != nil {
|
||
|
fmt.Println("Error save answer")
|
||
|
w.errChan <- err
|
||
|
}
|
||
|
|
||
|
case <-ctx.Done():
|
||
|
fmt.Println("Save for client worker terminated")
|
||
|
return
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (w *SaveForClient) saveAnswer(ctx context.Context, answer model.Answer) error {
|
||
|
answerJSON, err := json.Marshal(answer)
|
||
|
if err != nil {
|
||
|
fmt.Println("Error marshal answer to redis", err)
|
||
|
w.errChan <- err
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
key := fmt.Sprintf("answer:%d", time.Now().UnixNano())
|
||
|
|
||
|
err = w.deps.Redis.Set(ctx, key, answerJSON, 0).Err()
|
||
|
if err != nil {
|
||
|
fmt.Println("Error saving answer to redis", err)
|
||
|
w.errChan <- err
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|