github.com/kaydxh/golang@v0.0.131/pkg/database/redis/command.get.values.go (about) 1 /* 2 *Copyright (c) 2022, kaydxh 3 * 4 *Permission is hereby granted, free of charge, to any person obtaining a copy 5 *of this software and associated documentation files (the "Software"), to deal 6 *in the Software without restriction, including without limitation the rights 7 *to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 *copies of the Software, and to permit persons to whom the Software is 9 *furnished to do so, subject to the following conditions: 10 * 11 *The above copyright notice and this permission notice shall be included in all 12 *copies or substantial portions of the Software. 13 * 14 *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 *IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 *FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 *AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 *LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 *OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 *SOFTWARE. 21 */ 22 package redis 23 24 import ( 25 "context" 26 "fmt" 27 28 "github.com/go-redis/redis/v8" 29 ) 30 31 func GetValue(ctx context.Context, db *redis.Client, key string) ([]string, error) { 32 33 if db == nil { 34 return nil, fmt.Errorf("found unexpected nil redis client") 35 } 36 37 var values []string 38 39 typ, err := db.Type(ctx, key).Result() 40 if err != nil { 41 return nil, fmt.Errorf("failed to get type of key: %v, err: %v", key, err) 42 } 43 44 switch typ { 45 case "string": 46 data, err := db.Get(ctx, key).Result() 47 if err != nil { 48 return nil, fmt.Errorf("failed to get value of key: %v, err: %v", key, err) 49 } 50 values = append(values, data) 51 case "list": 52 llen, err := db.LLen(ctx, key).Result() 53 if err != nil { 54 return nil, fmt.Errorf("failed to get len of key: %v, err: %v", key, err) 55 } 56 57 var i int64 58 for i = 0; i < llen; i++ { 59 data, err := db.LIndex(ctx, key, i).Result() 60 if err != nil { 61 return nil, fmt.Errorf("failed to get list data of key: %v, err: %v", key, err) 62 } 63 values = append(values, data) 64 } 65 66 case "set": 67 members, err := db.SMembers(ctx, key).Result() 68 if err != nil { 69 return nil, fmt.Errorf("failed to get members of key: %v, err: %v", key, err) 70 } 71 values = append(values, members...) 72 73 default: 74 75 } 76 77 return values, nil 78 79 } 80 81 func GetValues(ctx context.Context, db *redis.Client, keys ...string) ([][]string, error) { 82 if db == nil { 83 return nil, fmt.Errorf("found unexpected nil redis client") 84 } 85 86 var values [][]string 87 88 for _, key := range keys { 89 90 value, err := GetValue(ctx, db, key) 91 if err != nil { 92 return nil, err 93 } 94 values = append(values, value) 95 } 96 97 return values, nil 98 99 }