REST Naming convention

This commit is contained in:
2024-07-25 13:51:19 +02:00
parent 83c519fdfd
commit 9a2673aba2
7 changed files with 140 additions and 167 deletions
+79 -1
View File
@@ -2,14 +2,17 @@
namespace Api\Users;
use Exception;
use Khofmann\Api\Api;
use Khofmann\Input\Input;
use Khofmann\Models\User\User;
use Khofmann\Response\Response;
use Khofmann\ApiError\ApiError;
use Khofmann\Request\Request;
class Users extends Api
{
public function get()
public function list()
{
// Fetch and constrain all parameters.
$page = max(0, intval(Input::get("p", 0)));
@@ -18,4 +21,79 @@ class Users extends Api
// Return list of users.
Response::json(User::list($page, $limit));
}
public function get($id): void
{
// Try and get a user, 404 if not found.
try {
Response::json(User::getByID($id));
} catch (Exception $err) {
switch ($err->getMessage()) {
case "NotFound":
throw ApiError::notFound("user");
default:
throw $err;
}
}
}
public function patch($id): void
{
// Fetch all inputs.
$username = Input::patch("username");
$password = Input::patch("password");
$image = Input::file("image");
// Try and update user.
// Throw errors according to situation.
try {
Response::json(User::getByID($id)->update($username, $password, $image));
} catch (Exception $err) {
switch ($err->getMessage()) {
case "NotFound":
throw ApiError::notFound("user");
default:
// Due to how the failed field is handled, it's ApiError is inside the models update
throw $err;
}
}
}
public function patchSelf(): void
{
// Fetch all inputs.
$token = Request::token();
$username = Input::patch("username");
$password = Input::patch("password");
$image = Input::file("image");
// Try and update user.
// Throw errors according to situation.
try {
Response::json(User::getByToken($token)->update($username, $password, $image));
} catch (Exception $err) {
switch ($err->getMessage()) {
case "NotFound":
throw ApiError::notFound("user");
default:
// Due to how the failed field is handled, it's ApiError is inside the models update
throw $err;
}
}
}
public function delete($id): void
{
// Try to delete user, 404 if not found.
try {
Response::json(User::getByID($id)->delete());
} catch (Exception $err) {
switch ($err->getMessage()) {
case "NotFound":
throw ApiError::notFound("user");
default:
throw $err;
}
}
}
}