Extract current user attributes into a separate serializer

This prevents the unread notifications count query being run for every
post by the currently authenticated user
This commit is contained in:
Toby Zerner 2015-06-01 12:25:40 +09:30
parent 39e1b8e008
commit 3eed9a99b6
3 changed files with 25 additions and 12 deletions

View File

@ -17,7 +17,7 @@ class ShowAction extends SerializeResourceAction
*
* @var string
*/
public static $serializer = 'Flarum\Api\Serializers\UserSerializer';
public static $serializer = 'Flarum\Api\Serializers\CurrentUserSerializer';
/**
* The relationships that are available to be included, and which ones are

View File

@ -0,0 +1,21 @@
<?php namespace Flarum\Api\Serializers;
class CurrentUserSerializer extends UserSerializer
{
protected function attributes($user)
{
$attributes = parent::attributes($user);
$actingUser = $this->actor->getUser();
if ($user->id === $actingUser->id) {
$attributes += [
'readTime' => $user->read_time ? $user->read_time->toRFC3339String() : null,
'unreadNotificationsCount' => $user->getUnreadNotificationsCount(),
'preferences' => $user->preferences
];
}
return $this->extendAttributes($user, $attributes);
}
}

View File

@ -12,8 +12,8 @@ class UserSerializer extends UserBasicSerializer
{
$attributes = parent::attributes($user);
$actorUser = $this->actor->getUser();
$canEdit = $user->can($actorUser, 'edit');
$actingUser = $this->actor->getUser();
$canEdit = $user->can($actingUser, 'edit');
$attributes += [
'bioHtml' => $user->bio_html,
@ -21,7 +21,7 @@ class UserSerializer extends UserBasicSerializer
'discussionsCount' => (int) $user->discussions_count,
'commentsCount' => (int) $user->comments_count,
'canEdit' => $canEdit,
'canDelete' => $user->can($actorUser, 'delete'),
'canDelete' => $user->can($actingUser, 'delete'),
];
if ($user->preference('discloseOnline')) {
@ -39,14 +39,6 @@ class UserSerializer extends UserBasicSerializer
];
}
if ($user->id === $actorUser->id) {
$attributes += [
'readTime' => $user->read_time ? $user->read_time->toRFC3339String() : null,
'unreadNotificationsCount' => $user->getUnreadNotificationsCount(),
'preferences' => $user->preferences
];
}
return $this->extendAttributes($user, $attributes);
}
}