refactor: cache some more queries

This commit is contained in:
b1ek 2024-08-30 18:24:26 +10:00
parent 9a2ca7e184
commit 6621dd4772
Signed by: blek
GPG Key ID: 14546221E3595D0C
2 changed files with 12 additions and 6 deletions

View File

@ -9,7 +9,7 @@ class AuthorizedRequest extends RestRequest
*/ */
public function authorize(): bool public function authorize(): bool
{ {
return cache()->remember('isSessionAuthorized'.session()->id(), 5, function(){ return cache()->remember('isSessionAuthorized'.session()->id(), 5, function () {
return auth()->check(); return auth()->check();
}); });
} }

View File

@ -50,7 +50,9 @@ class UserService
public function setPassword($data) public function setPassword($data)
{ {
$user = User::where(['email' => $data['email']])->first(); $user = cache()->remember('userExists'.$data['email'], 5, function () use ($data) {
return User::where(['email' => $data['email']])->first();
});
if ($user === null) { if ($user === null) {
return; return;
} }
@ -62,21 +64,23 @@ class UserService
public function listAll(?Filters $filters = null): array public function listAll(?Filters $filters = null): array
{ {
if (is_null($filters)) { if (is_null($filters)) {
return cache()->remember('usersListAll', 15, function() { return cache()->remember('usersListAll', 15, function () {
return User::all()->toArray(); return User::all()->toArray();
}); });
} }
$builder = User::query(); $builder = User::query();
$filters->apply($builder); $filters->apply($builder);
return cache()->remember('usersListFilter'.$filters->hash(), 15, function() use ($builder) { return cache()->remember('usersListFilter'.$filters->hash(), 15, function () use ($builder) {
return $builder->get()->toArray(); return $builder->get()->toArray();
}); });
} }
public function getOneById(string $id): ?User public function getOneById(string $id): ?User
{ {
return User::where(['id' => $id])->first(); return cache()->remember('userId'.$id, 5, function () use ($id) {
return User::where(['id' => $id])->first();
});
} }
/** /**
@ -102,7 +106,9 @@ class UserService
public function getUnexistingIds(array $ids): ?array public function getUnexistingIds(array $ids): ?array
{ {
$users = User::whereIn('id', $ids)->get(); $users = cache()->remember('userWhereIn'.implode(',', $ids), 5, function () use ($ids) {
User::whereIn('id', $ids)->get();
});
if ($users->count() != count($ids)) { if ($users->count() != count($ids)) {
$existingIds = $users->map( $existingIds = $users->map(
function ($model) { function ($model) {