From 3a828a623f6eb88d4397aa8954a6112233300325 Mon Sep 17 00:00:00 2001 From: Julian Prieber <60265788+JulianPrieber@users.noreply.github.com> Date: Sat, 16 Dec 2023 19:09:38 +0100 Subject: [PATCH] Caching requests --- app/Models/UserData.php | 35 ++++++++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/app/Models/UserData.php b/app/Models/UserData.php index 226718a..6b21dc9 100644 --- a/app/Models/UserData.php +++ b/app/Models/UserData.php @@ -3,6 +3,7 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Facades\Cache; class UserData extends Model { @@ -11,7 +12,7 @@ class UserData extends Model public static function saveData($userId, $key, $value) { - $userData = self::where('id', $userId)->first(); + $userData = self::getCachedUserData($userId); if (!$userData) { return "null"; @@ -22,35 +23,51 @@ class UserData extends Model $userData->image = json_encode($data); $userData->save(); + + self::cacheUserData($userId, $userData); } public static function getData($userId, $key) { - $userData = self::where('id', $userId)->first(); - + $userData = self::getCachedUserData($userId); + if (!$userData || !$userData->image) { return "null"; } - + $data = json_decode($userData->image, true) ?? []; - + return isset($data[$key]) ? $data[$key] : null; } public static function removeData($userId, $key) { - $userData = self::where('id', $userId)->first(); - + $userData = self::getCachedUserData($userId); + if (!$userData || !$userData->image) { return "null"; } - + $data = json_decode($userData->image, true) ?? []; - + if (isset($data[$key])) { unset($data[$key]); $userData->image = json_encode($data); $userData->save(); + + self::cacheUserData($userId, $userData); } } + + private static function getCachedUserData($userId) + { + return Cache::remember('user_data_' . $userId, now()->addMinutes(10), function () use ($userId) { + return self::where('id', $userId)->first(); + }); + } + + private static function cacheUserData($userId, $userData) + { + Cache::put('user_data_' . $userId, $userData, now()->addMinutes(10)); + } }