Update StatusHashtagService, use more efficient cached count

This commit is contained in:
Daniel Supernault 2024-03-07 02:37:35 -07:00
parent e68fe64ffc
commit 592c84125c
No known key found for this signature in database
GPG key ID: 23740873EE6F76A1

View file

@ -2,22 +2,20 @@
namespace App\Services;
use Cache;
use Illuminate\Support\Facades\Redis;
use App\{Status, StatusHashtag};
use App\Transformer\Api\StatusHashtagTransformer;
use App\Hashtag;
use App\Status;
use App\StatusHashtag;
use App\Transformer\Api\HashtagTransformer;
use League\Fractal;
use League\Fractal\Serializer\ArraySerializer;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
class StatusHashtagService {
class StatusHashtagService
{
const CACHE_KEY = 'pf:services:status-hashtag:collection:';
public static function get($id, $page = 1, $stop = 9)
{
if($page > 20) {
if ($page > 20) {
return [];
}
@ -33,11 +31,11 @@ class StatusHashtagService {
->map(function ($i, $k) use ($id) {
return self::getStatus($i, $id);
})
->filter(function ($i) use($filtered) {
->filter(function ($i) use ($filtered) {
return isset($i['status']) &&
!empty($i['status']) && !in_array($i['status']['account']['id'], $filtered) &&
! empty($i['status']) && ! in_array($i['status']['account']['id'], $filtered) &&
isset($i['status']['media_attachments']) &&
!empty($i['status']['media_attachments']);
! empty($i['status']['media_attachments']);
})
->values();
}
@ -52,9 +50,10 @@ class StatusHashtagService {
->skip($start)
->take($stop)
->pluck('status_id');
foreach($ids as $key) {
foreach ($ids as $key) {
self::set($id, $key);
}
return $ids;
}
@ -70,11 +69,12 @@ class StatusHashtagService {
public static function count($id)
{
$key = 'pf:services:status-hashtag:count:' . $id;
$ttl = now()->addMinutes(5);
return Cache::remember($key, $ttl, function() use($id) {
return StatusHashtag::whereHashtagId($id)->has('media')->count();
});
$cc = Hashtag::find($id);
if (! $cc) {
return 0;
}
return $cc->cached_count ?? 0;
}
public static function getStatus($statusId, $hashtagId)
@ -85,13 +85,14 @@ class StatusHashtagService {
public static function statusTags($statusId)
{
$status = Status::with('hashtags')->find($statusId);
if(!$status) {
if (! $status) {
return [];
}
$fractal = new Fractal\Manager();
$fractal->setSerializer(new ArraySerializer());
$resource = new Fractal\Resource\Collection($status->hashtags, new HashtagTransformer());
return $fractal->createData($resource)->toArray();
}
}