I have a requirement to expose a specific content type data via REST end point. Below is my code:
public function get() {
$current_user = $this->currentUser->id();
$user = $this->entityTypeManager->getStorage('user')->load($current_user);
$userLangId = $user->language()->getId();
// You must to implement the logic of your REST Resource here.
// Use current user after pass authentication to validate access.
if (!$this->currentUser->hasPermission('access content')) {
throw new AccessDeniedHttpException();
}
$news_values = [
'langcode' => $userLangId,
'type' => ['story'],
'status' => 1,
];
$news_data = $this->entityTypeManager->getStorage('node')->loadByProperties($news_values);
$newsfeed = [];
$newsfeed['stories'] = ['Story' => array_values($news_data)];
if (empty($newsfeed)) {
return new ResourceResponse('No Newsfeed exist for this user.', 400);
}
$response = new ResourceResponse($newsfeed, 200);
// $response->addCacheableDependency($current_user);
$response->addCacheableDependency(CacheableMetadata::createFromRenderArray([
'#cache' => [
'context' => ['user.roles'],
'tags' => ['user:3', 'languages:' . $userLangId],
],
]));
return $response;
}
I am getting a proper response with this but I am facing issues in handling the cache. This content is user specific. Based on user language content will popup when they access.
In Response Headers I am getting below things:
X-Drupal-Cache-Contexts: languages:language_interface theme url.site user.permissions
X-Drupal-Cache-Tags: config:filter.format.basic_html config:rest.resource.newsfeed_rest_resource config:rest.settings config:system.site http_response languages:fr node:7 node:9 user:3
X-Drupal-Dynamic-Cache: MISS/HIT
In Cache-tags i have not added node key but its automatically coming and its working once node updated. But if i try to login with different user via basic auth
on postman client, content is not changing at all. Its showing cached content for previous user. How I can cache the content per user. Please help me in this regard.
['user.roles']
to['user']
and clear your caches should work