Initial cloud-services repo - gateway service + pkg modules
This commit is contained in:
60
pkg/cachev2/verify.go
Normal file
60
pkg/cachev2/verify.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package cachev2
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"fiskerinc.com/modules/common"
|
||||
"fiskerinc.com/modules/db/queries"
|
||||
redis "fiskerinc.com/modules/redisv2"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// VerifyCarToDriver checks cache and DB for car to driver relationship.
|
||||
// If relationship exists and not in cache, will cache value.
|
||||
//
|
||||
// car:<VIN>:driver:<DRIVER_ID>
|
||||
func VerifyCarToDriver(clientPool redis.ClientInterface, db queries.CarsInterface, vin string, driverID string) (bool, error) {
|
||||
key := redis.CarToDriverKey(vin, driverID)
|
||||
|
||||
ok, err := redisCheckGet(clientPool, key)
|
||||
if err != nil {
|
||||
return ok, err
|
||||
}
|
||||
|
||||
if ok {
|
||||
return ok, err
|
||||
}
|
||||
|
||||
carToDrivers, err := db.SelectCarToDriver(&common.CarToDriver{VIN: vin, DriverID: driverID})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
verified := len(carToDrivers) == 1
|
||||
redisPlaceDriverCache(clientPool, key, verified)
|
||||
|
||||
return verified, err
|
||||
}
|
||||
|
||||
func redisCheckGet(redisClient redis.ClientInterface, key string) (bool, error) {
|
||||
value, err := redisClient.Get(key)
|
||||
if err != nil {
|
||||
if errors.Is(err, redis.ErrNil) {
|
||||
err = nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
v, ok := value.(bool)
|
||||
if !ok {
|
||||
err = fmt.Errorf("failed to convert %v interface to bool", value)
|
||||
}
|
||||
return v, err
|
||||
}
|
||||
|
||||
func redisPlaceDriverCache(redisClient redis.ClientInterface, key string, verified bool) (err error) {
|
||||
batch := redis.NewRedisBatchCommands()
|
||||
batch.Add(redis.Command{Command: "SET", Arguments: []interface{}{key, verified}})
|
||||
batch.Add(redis.Command{Command: "EXPIRE", Arguments: []interface{}{key, redisObjectExpire.Seconds()}})
|
||||
_, err = redisClient.ExecuteBatch(batch)
|
||||
return
|
||||
}
|
||||
Reference in New Issue
Block a user