craftcms / element-api

Create a JSON API/Feed for your elements in Craft.
MIT License
498 stars 56 forks source link

fix: Do not use the cache when preview mode is enabled. #144

Closed Zae closed 2 years ago

Zae commented 3 years ago

Description

When preview mode is enabled in the request do not try to fetch from or write to the cache, this fixes possibly fetching stale content or writing draft content to the cache.

Note: I'm using getToken() instead of isPreview, because isPreview returns false when using the X-Craft-Token header.

Related issues

Fixes #143

carlcs commented 2 years ago

Preview requests can probably be excluded by default from being cached. I guess the same also applies to environments where devMode is enabled.

But if the default configuration doesn’t work for you, it’s always possible to configure caching behaviour via the config file. We are disabling caching in dev environments, for example.

return [
    'defaults' => function() {
        $isDev = getenv('ENVIRONMENT') === 'dev';
        return [
            'cache' => $isDev ? false : 'P1Y', // one year
        ];
    },
    'endpoints' => [],
];
brandonkelly commented 2 years ago

Thanks for the PR! Just released Element API 2.8.0 which solves this.