laravel-json-api / laravel

JSON:API for Laravel applications
MIT License
523 stars 43 forks source link

Best location to add cache for API get requests #269

Closed ssglopes closed 4 months ago

ssglopes commented 4 months ago

Hi, Using this package for api request. Trying to add caching to reduce DB lookups with this package LaraGear CacheQuery. Could you maybe recommend where in your package this would be best added. For example to cache all posts to redis something like this needs to be added somewhere in your code: Post::cache(null, Post::class). Tried to find the best place but so far without luck. I looked into adding a scope but it fails with an error:

class Server extends BaseServer {
......
public function serving(): void
    {
        ....
        Post::addGlobalScope(new CacheScope());
       .....

The CacheScope:

class CacheScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        // cache indefinite with key App\Models\Post
        $builder->cache(null, $model::class);
    }
}

The error i get: Lost connection and no reconnector available.

Any recommendation or hints in the right direction would be much appreciated.

Thanks.

lindyhopchris commented 4 months ago

Hi! Sorry, but I can't provide any advice on using that cache query package. You'd need to ask in that package as to why it isn't working in a global scope.

For caching generally you'd get more benefit if you use HTTP caching, because it would mean on a replayed request non of the Laravel JSON:API code would need to execute again. HTTP caching is usually implemented via middleware, which makes it easy to use for the Laravel JSON:API routes. Here is an example package: https://github.com/spatie/laravel-responsecache

ssglopes commented 4 months ago

Hi @lindyhopchris thanks for your feedback so fast. Was also looking into that package already as maybe a better alternative. Thanks again and have a nice week ahead.