|
1 | 1 | package repository
|
2 | 2 |
|
3 |
| -import "github.com/go-redis/redis/v9" |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "github.com/Programmer-RD-AI/auth-forge/internal/errors" |
| 7 | + "github.com/Programmer-RD-AI/auth-forge/pkg/util" |
| 8 | + "github.com/redis/go-redis/v9" |
| 9 | +) |
4 | 10 |
|
5 | 11 | type RedisConfiguration struct {
|
6 |
| - Host string |
| 12 | + Host string |
7 | 13 | Port int
|
8 | 14 | Password string
|
9 | 15 | Database int
|
10 | 16 | }
|
11 | 17 |
|
12 | 18 | type RedisRepository struct {
|
| 19 | + BaseRepository |
13 | 20 | config RedisConfiguration
|
14 | 21 | client *redis.Client
|
15 | 22 | }
|
16 | 23 |
|
17 |
| -func CreateRedisConfiguration(host *string, port *int, password *string, database *int){} |
| 24 | +func CreateRedisConfiguration(host *string, port *int, password *string, database *int) RedisConfiguration { |
| 25 | + if host == nil { |
| 26 | + h, _ := util.GetEnv[string]("REDIS_HOST", "localhost") |
| 27 | + host = &h |
| 28 | + } |
| 29 | + if port == nil { |
| 30 | + p, _ := util.GetEnv[int]("REDIS_PORT", 6379) |
| 31 | + port = &p |
| 32 | + } |
| 33 | + if password == nil { |
| 34 | + pass, _ := util.GetEnv[string]("REDIS_PASSWORD", "") |
| 35 | + password = &pass |
| 36 | + } |
| 37 | + if database == nil { |
| 38 | + db, _ := util.GetEnv[int]("REDIS_DATABASE", 0) |
| 39 | + database = &db |
| 40 | + } |
| 41 | + return RedisConfiguration{ |
| 42 | + Host: *host, |
| 43 | + Port: *port, |
| 44 | + Password: *password, |
| 45 | + Database: *database, |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +func (r *RedisRepository) Connect() (*redis.Client, context.Context) { |
| 50 | + redisClient := redis.NewClient(createRedisOption(&r.config)) |
| 51 | + initCtx := context.Background() |
| 52 | + return redisClient, initCtx |
| 53 | +} |
18 | 54 |
|
19 |
| -func (r *RedisReppository) Connect(){ |
20 |
| - return redis.NewClient(createRedisOption(r.config)); |
| 55 | +func (r *RedisRepository) HealthCheck(ctx context.Context, client *redis.Client) (bool, error) { |
| 56 | + if err := client.Ping(ctx).Err(); err != nil { |
| 57 | + return false, errors.dbHealthCheckFail{message: err.Error(), provider: r.BaseRepository.providerName} |
| 58 | + } |
| 59 | + return true, nil |
21 | 60 | }
|
22 | 61 |
|
| 62 | +func (r *RedisRepository) Read(client *redis.Client, ctx context.Context, key *string){ |
| 63 | + val, err := client.Get(ctx, *key).Result() |
| 64 | +} |
23 | 65 | func createRedisOption(redisConfig *RedisConfiguration) *redis.Options {
|
24 | 66 | return &redis.Options{
|
25 |
| - Addr: fmt.Sprintf("%s:%d", redisConfig.Host, redisConfig.Port) |
26 |
| - Password: redisConfig.Password |
27 |
| - DB: redisConfig.Database |
| 67 | + Addr: fmt.Sprintf("%s:%d", redisConfig.Host, redisConfig.Port), |
| 68 | + Password: redisConfig.Password, |
| 69 | + DB: redisConfig.Database, |
28 | 70 | }
|
29 | 71 | }
|
0 commit comments