Skip to content

Commit

Permalink
feat(feed): Add a unfollow a topic API
Browse files Browse the repository at this point in the history
  • Loading branch information
medz committed Jul 24, 2018
1 parent 435baf5 commit 41b74b0
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
49 changes: 49 additions & 0 deletions app/API2/Controllers/Feed/TopicFollow.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,53 @@ public function follow(Request $request, FeedTopicModel $model, int $topicID): R
return $response;
});
}

/**
* Unfollow a topic.
*
* @param \Illuminate\Http\Request $request
* @param \Zhiyi\Plus\Models\FeedTopic $model
* @param int $topicID
* @return \Illuminate\Http\Response
*/
public function unfollow(Request $request, FeedTopicModel $model, int $topicID): Response
{
// Featch the request authentication user model.
$user = $request->user();

// Database query topic.
$topic = $model
->query()
->where('id', $topicID)
->first();

// If the topic Non-existent, throw a not found exception.
if (! $topic) {
throw new NotFoundHttpException('关注的话题不存在');
}

// Create success 204 response
$response = (new Response())->setStatusCode(Response::HTTP_NO_CONTENT /* 204 */);

// Database query the authentication user followed.
$exists = $topic
->followers()
->where('user_id', $user->id)
->exists();

// If not followed, return 204 response.
if (! $exists) {
return $response;
}

return $user->getConnection()->transaction(function () use ($user, $topic, $response): Response {
$topic->followers()->detach($user);

if ($topic->followers_count > 0) {
$topic->decrement('followers_count', 1);
}

return $response;
});
}
}
8 changes: 8 additions & 0 deletions routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -668,4 +668,12 @@
* @Response::header('Status', 204, 'No Content')
*/
$api->put('user/feed-topics/{topicID}', \Zhiyi\Plus\API2\Controllers\Feed\TopicFollow::class.'@follow');

/*
* Unfollow a topic
*
* @Delete /api/v2/user/feed-topics/:topicID
* @Response::header('Status', 204, 'No Content')
*/
$api->delete('user/feed-topics/{topicID}', \Zhiyi\Plus\API2\Controllers\Feed\TopicFollow::class.'@unfollow');
});

0 comments on commit 41b74b0

Please sign in to comment.