[TASK] improve draft of ProductExists
This commit is contained in:
parent
9da367ff5a
commit
ff299c42a7
|
@ -1,6 +1,36 @@
|
|||
package models
|
||||
|
||||
// TODO DRAFT for a rest request to a other microservice
|
||||
func ProductExists(id int64) (bool, error) {
|
||||
return true, nil
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type boolMicroServiceCache struct {
|
||||
LastCheck time.Time
|
||||
Value bool
|
||||
}
|
||||
|
||||
var productExistCache map[int64]boolMicroServiceCache
|
||||
|
||||
func init() {
|
||||
productExistCache = make(map[int64]boolMicroServiceCache)
|
||||
}
|
||||
|
||||
func ProductExists(id int64) (bool, error) {
|
||||
if cache, ok := productExistCache[id]; ok {
|
||||
// cache for 5min
|
||||
before := time.Now().Add(-time.Minute * 5)
|
||||
if !cache.LastCheck.Before(before) {
|
||||
return cache.Value, nil
|
||||
}
|
||||
}
|
||||
|
||||
// TODO DRAFT for a rest request to a other microservice
|
||||
res, err := http.Get("http://golang.org")
|
||||
|
||||
productExistCache[id] = boolMicroServiceCache{
|
||||
LastCheck: time.Now(),
|
||||
Value: (res.StatusCode == http.StatusOK),
|
||||
}
|
||||
return productExistCache[id].Value, err
|
||||
}
|
||||
|
|
|
@ -8,8 +8,15 @@ import (
|
|||
|
||||
func TestProductExists(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
ok, err := ProductExists(3)
|
||||
|
||||
ok, err := ProductExists(3)
|
||||
assert.True(ok)
|
||||
assert.NoError(err)
|
||||
|
||||
// test cache
|
||||
ok, err = ProductExists(3)
|
||||
assert.True(ok)
|
||||
assert.NoError(err)
|
||||
|
||||
// WARNING: test cache after 5min skipped
|
||||
}
|
||||
|
|
Reference in New Issue