Better Errors
This commit is contained in:
@@ -2,9 +2,12 @@
|
||||
|
||||
namespace Api\Posts;
|
||||
|
||||
use Exception;
|
||||
use Khofmann\Api\Api;
|
||||
use Khofmann\ApiError\ApiError;
|
||||
use Khofmann\Input\Input;
|
||||
use Khofmann\Models\Post\Post;
|
||||
use Khofmann\Models\User\User;
|
||||
use Khofmann\Request\Request;
|
||||
use Khofmann\Response\Response;
|
||||
|
||||
@@ -12,10 +15,33 @@ class Posts extends Api
|
||||
{
|
||||
public function get()
|
||||
{
|
||||
// Fetch and constrain all parameters.
|
||||
$page = max(0, intval(Input::get("p", 0)));
|
||||
$limit = constrain(0, 30, intval(Input::get("l", 10)));
|
||||
$authed = Request::token() !== null;
|
||||
|
||||
// Return list of posts.
|
||||
Response::json(Post::list($page, $limit, $authed));
|
||||
}
|
||||
|
||||
public function post(): void
|
||||
{
|
||||
// Fetch all required inputs.
|
||||
// Throw 400 error if a required one is missing.
|
||||
$content = Input::post("content");
|
||||
if (empty($content)) throw ApiError::missingField(["content"]);
|
||||
|
||||
// Get logged in user
|
||||
$self = User::getByToken(Request::token());
|
||||
|
||||
// Try to create a new post for logged in user.
|
||||
try {
|
||||
Response::json(Post::create($self, $content));
|
||||
} catch (Exception $err) {
|
||||
switch ($err->getMessage()) {
|
||||
default:
|
||||
throw $err;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user