made edlp_ajax response cachable

This commit is contained in:
Bachir Soussi Chiadmi
2018-04-03 22:14:53 +02:00
parent 3c72614b3f
commit c794046eca
@@ -6,7 +6,10 @@ use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Url;
use Drupal\menu_link_content\Entity\MenuLinkContent;
use Symfony\Component\HttpFoundation\JsonResponse;
// use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\core\render\RenderContext;
class EdlpAjaxController extends ControllerBase {
@@ -43,7 +46,12 @@ class EdlpAjaxController extends ControllerBase {
$this->viewmode = $viewmode;
$renderable = $this->toRenderable();
$rendered = render($renderable);
// $rendered = render($renderable);
// We can't render directly the entity as it throw an exception with cachable data
// see http://blog.dcycle.com/blog/2018-01-24/caching-drupal-8-rest-resource/#the-dreaded-leaked-metadata-error
$rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($renderable) {
return render($renderable);
});
switch($this->entity_type){
case 'node':
@@ -57,7 +65,7 @@ class EdlpAjaxController extends ControllerBase {
}
$data = [
'test' => 'hello edlp ajax',
'date' => time(),
'id' => $this->id,
'view_mode' => $this->viewmode,
'bundle' => $bundle,
@@ -83,16 +91,30 @@ class EdlpAjaxController extends ControllerBase {
$menu_parents[] = $sys_path;
}
}
$data['menu_parents'] = $menu_parents;
// $data['menu_parents'] = $menu_parents;
}
$response = new JsonResponse();
$response->setData($data);
$data['#cache'] = [
'max-age' => \Drupal\Core\Cache\Cache::PERMANENT,
'tags' => [
'edlp-ajax-cache',
// $this->entity_type.':'.$this->id // not necessary as we add $renderable as CacheableMetadata to the response
]
];
// $response = new JsonResponse();
// $response->setData($data);
$response = new CacheableJsonResponse($data);
$response->addCacheableDependency(CacheableMetadata::createFromRenderArray($renderable));
$response->addCacheableDependency(CacheableMetadata::createFromRenderArray($data));
return $response;
// return array(
// '#markup'=>'hello'
// );
dpm($response);
return array(
'#markup'=>'hello'
);
}
}