Skip to content

Commit

Permalink
feat: cache oembed results
Browse files Browse the repository at this point in the history
  • Loading branch information
andreiio committed Dec 14, 2023
1 parent 65efe42 commit ee7972c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 22 deletions.
23 changes: 12 additions & 11 deletions app/Models/BCRProject.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Vite;
use Spatie\Image\Manipulations;
use Spatie\MediaLibrary\HasMedia;
Expand Down Expand Up @@ -86,17 +87,17 @@ public function category(): BelongsTo

public function getEmbeddedVideosAttribute(): array
{
$videos = $this->videos;
$embeddedVideos = [];
if (empty($videos)) {
return [];
}
foreach ($videos as $video) {
$embeddedUrl = rescue(fn () => (new Embed())->get($video['link'])->code, null);
$embeddedVideos[] = $embeddedUrl;
}

return collect($embeddedVideos)->filter(fn ($item) => ! empty($item))->toArray();
return collect($this->videos)
->pluck('link')
->map(
fn (string $videoUrl) => Cache::remember(
'video-' . hash('sha256', $videoUrl),
MONTH_IN_SECONDS,
fn () => rescue(fn () => (new Embed)->get($videoUrl)->code, '', false)
)
)
->filter()
->all();
}

//TODO MOVE IN TRAIT
Expand Down
23 changes: 12 additions & 11 deletions app/Models/Project.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Vite;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;
Expand Down Expand Up @@ -275,17 +276,17 @@ public function markAsRejected(?string $reason = null): void

public function getEmbeddedVideosAttribute(): array
{
$videos = $this->videos;
$embeddedVideos = [];
if (empty($videos)) {
return [];
}
foreach ($videos as $video) {
$embeddedUrl = rescue(fn () => (new Embed())->get($video['url'])->code, '');
$embeddedVideos[] = $embeddedUrl;
}

return $embeddedVideos;
return collect($this->videos)
->pluck('url')
->map(
fn (string $videoUrl) => Cache::remember(
'video-' . hash('sha256', $videoUrl),
MONTH_IN_SECONDS,
fn () => rescue(fn () => (new Embed)->get($videoUrl)->code, '', false)
)
)
->filter()
->all();
}

public function scopeSearch(Builder $query, ?string $search): Builder
Expand Down

0 comments on commit ee7972c

Please sign in to comment.