Added new API Endpoint to manually queue to run task.

This commit is contained in:
Abdulmhsen B. A. A
2024-04-24 03:09:48 +03:00
parent 1fb3efbad9
commit 8a0adabda6
2 changed files with 70 additions and 4 deletions

View File

@@ -6,14 +6,22 @@ namespace App\API\Tasks;
use App\Commands\System\TasksCommand;
use App\Libs\Attributes\Route\Get;
use App\Libs\Attributes\Route\Route;
use App\Libs\HTTP_STATUS;
use DateInterval;
use Psr\Http\Message\ResponseInterface as iResponse;
use Psr\Http\Message\ServerRequestInterface as iRequest;
use Psr\SimpleCache\CacheInterface as iCache;
use Psr\SimpleCache\InvalidArgumentException;
final class Index
{
public const string URL = '%{api.prefix}/tasks';
public function __construct(private readonly iCache $cache)
{
}
#[Get(self::URL . '[/]', name: 'tasks.index')]
public function tasksIndex(iRequest $request): iResponse
{
@@ -36,6 +44,7 @@ final class Index
$task['links'] = [
'self' => (string)$apiUrl->withPath($urlPath . '/' . ag($task, 'name')),
'queue' => (string)$apiUrl->withPath($urlPath . '/' . ag($task, 'name') . '/queue'),
];
$response['tasks'][] = $task;
@@ -44,8 +53,46 @@ final class Index
return api_response(HTTP_STATUS::HTTP_OK, $response);
}
#[Get(self::URL . '/{id:[a-zA-Z0-9_-]+}[/]', name: 'tasks.view')]
public function __invoke(iRequest $request, array $args = []): iResponse
/**
* @throws InvalidArgumentException
*/
#[Route(['GET', 'POST'], self::URL . '/{id:[a-zA-Z0-9_-]+}/queue[/]', name: 'tasks.task.queue')]
public function taskQueue(iRequest $request, array $args = []): iResponse
{
if (null === ($id = ag($args, 'id'))) {
return api_error('No id was given.', HTTP_STATUS::HTTP_BAD_REQUEST);
}
$task = TasksCommand::getTasks($id);
if (empty($task)) {
return api_error('Task not found.', HTTP_STATUS::HTTP_NOT_FOUND);
}
$queuedTasks = $this->cache->get('queued_tasks', []);
if ('POST' === $request->getMethod()) {
$queuedTasks[] = $id;
$this->cache->set('queued_tasks', $queuedTasks, new DateInterval('P3D'));
return api_response(HTTP_STATUS::HTTP_ACCEPTED, ['queue' => $queuedTasks]);
}
$apiUrl = $request->getUri()->withHost('')->withPort(0)->withScheme('')->withUserInfo('');
$urlPath = parseConfigValue(Index::URL);
return api_response(HTTP_STATUS::HTTP_OK, [
'task' => $id,
'is_queued' => in_array($id, $queuedTasks),
'links' => [
'self' => (string)$apiUrl,
'task' => (string)$apiUrl->withPath($urlPath . '/' . $id),
'tasks' => (string)$apiUrl->withPath($urlPath),
],
]);
}
#[Get(self::URL . '/{id:[a-zA-Z0-9_-]+}[/]', name: 'tasks.task.view')]
public function taskView(iRequest $request, array $args = []): iResponse
{
if (null === ($id = ag($args, 'id'))) {
return api_error('No id was given.', HTTP_STATUS::HTTP_BAD_REQUEST);