package adapter import ( "bytes" "context" "encoding/gob" "errors" "fmt" "time" "gitea.dwysokinski.me/twhelp/dcbot/internal/domain" "github.com/redis/go-redis/v9" ) type VillageRedis struct { client redis.UniversalClient } func NewVillageRedis(client redis.UniversalClient) *VillageRedis { return &VillageRedis{client: client} } const translateVillageCoordsParamsExp = 72 * time.Hour type translateVillageCoordsParamsRedis struct { VersionCode string ServerKey string Coords []string PerPage int32 MaxPage int32 SHA256 string } func (v *VillageRedis) SaveTranslateCoordsParams(ctx context.Context, params domain.TranslateVillageCoordsParams) error { buf := bytes.NewBuffer(nil) if err := gob.NewEncoder(buf).Encode(translateVillageCoordsParamsRedis{ VersionCode: params.VersionCode(), ServerKey: params.ServerKey(), Coords: params.Coords(), PerPage: params.PerPage(), MaxPage: params.MaxPage(), SHA256: params.SHA256(), }); err != nil { return err } if err := v.client.Set( ctx, v.buildTranslateCoordsParamsKey(params.SHA256()), buf.Bytes(), translateVillageCoordsParamsExp, ).Err(); err != nil { return err } return nil } func (v *VillageRedis) GetTranslateCoordsParams(ctx context.Context, sha256Hash string) (domain.TranslateVillageCoordsParams, error) { b, err := v.client.Get(ctx, v.buildTranslateCoordsParamsKey(sha256Hash)).Bytes() if errors.Is(err, redis.Nil) { return domain.TranslateVillageCoordsParams{}, domain.TranslateVillageCoordsParamsNotFoundError{ SHA256: sha256Hash, } } if err != nil { return domain.TranslateVillageCoordsParams{}, err } var params translateVillageCoordsParamsRedis if err = gob.NewDecoder(bytes.NewReader(b)).Decode(¶ms); err != nil { return domain.TranslateVillageCoordsParams{}, err } res, err := domain.UnmarshalTranslateVillageCoordsParamsFromDatabase( params.VersionCode, params.ServerKey, params.Coords, params.PerPage, params.MaxPage, params.SHA256, ) if err != nil { return domain.TranslateVillageCoordsParams{}, fmt.Errorf("couldn't unmarshal TranslateVillageCoordsParams from database: %w", err) } return res, nil } func (v *VillageRedis) buildTranslateCoordsParamsKey(sha256Hash string) string { return "translate_village_coords_params_" + sha256Hash }