jokes-bapak2/api/app/core/joke_setter.go

56 lines
1016 B
Go
Raw Normal View History

2021-07-19 10:21:08 +00:00
package core
import (
2021-09-27 10:10:19 +00:00
"context"
2021-07-19 10:21:08 +00:00
"github.com/allegro/bigcache/v3"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/pquerna/ffjson/ffjson"
)
// SetAllJSONJoke fetches jokes data from GetAllJSONJokes then set it to memory cache.
2021-09-27 10:10:19 +00:00
func SetAllJSONJoke(db *pgxpool.Pool, memory *bigcache.BigCache, ctx *context.Context) error {
jokes, err := GetAllJSONJokes(db, ctx)
2021-07-19 10:21:08 +00:00
if err != nil {
return err
}
err = memory.Set("jokes", jokes)
if err != nil {
return err
}
return nil
}
2021-09-27 10:10:19 +00:00
func SetTotalJoke(db *pgxpool.Pool, memory *bigcache.BigCache, ctx *context.Context) error {
2021-07-19 10:21:08 +00:00
check, err := CheckJokesCache(memory)
if err != nil {
return err
}
if !check {
2021-09-27 10:10:19 +00:00
err = SetAllJSONJoke(db, memory, ctx)
2021-07-19 18:35:30 +00:00
if err != nil {
return err
}
2021-07-19 10:21:08 +00:00
}
jokes, err := memory.Get("jokes")
if err != nil {
return err
}
var data []Joke
2021-07-19 10:21:08 +00:00
err = ffjson.Unmarshal(jokes, &data)
if err != nil {
return err
}
var total = []byte{byte(len(data))}
err = memory.Set("total", total)
if err != nil {
return err
}
return nil
}