Added option to filter by date in visits REST endpoint

This commit is contained in:
Alejandro Celaya 2016-07-21 10:13:09 +02:00
parent bdd2d6f8b2
commit 0ef9db0bdf
2 changed files with 22 additions and 2 deletions

View File

@ -225,6 +225,9 @@ Posible errors:
* `GET` -> `/rest/visits/{shortCode}` * `GET` -> `/rest/visits/{shortCode}`
* Route params: * Route params:
* shortCode: `string` -> The shortCode from which we eant to get the visits. * shortCode: `string` -> The shortCode from which we eant to get the visits.
* Query params:
* startDate: `string` -> If provided, only visits older that this date will be returned
* endDate: `string` -> If provided, only visits newer that this date will be returned
* Headers: * Headers:
* X-Auth-Token: `string` -> The token provided in the authentication request * X-Auth-Token: `string` -> The token provided in the authentication request

View File

@ -5,6 +5,7 @@ use Acelaya\ZsmAnnotatedServices\Annotation\Inject;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
use Shlinkio\Shlink\Common\Exception\InvalidArgumentException; use Shlinkio\Shlink\Common\Exception\InvalidArgumentException;
use Shlinkio\Shlink\Common\Util\DateRange;
use Shlinkio\Shlink\Core\Service\VisitsTracker; use Shlinkio\Shlink\Core\Service\VisitsTracker;
use Shlinkio\Shlink\Core\Service\VisitsTrackerInterface; use Shlinkio\Shlink\Core\Service\VisitsTrackerInterface;
use Shlinkio\Shlink\Rest\Util\RestUtils; use Shlinkio\Shlink\Rest\Util\RestUtils;
@ -37,14 +38,15 @@ class GetVisitsMiddleware extends AbstractRestMiddleware
public function dispatch(Request $request, Response $response, callable $out = null) public function dispatch(Request $request, Response $response, callable $out = null)
{ {
$shortCode = $request->getAttribute('shortCode'); $shortCode = $request->getAttribute('shortCode');
$startDate = $this->getDateQueryParam($request, 'startDate');
$endDate = $this->getDateQueryParam($request, 'endDate');
try { try {
$visits = $this->visitsTracker->info($shortCode); $visits = $this->visitsTracker->info($shortCode, new DateRange($startDate, $endDate));
return new JsonResponse([ return new JsonResponse([
'visits' => [ 'visits' => [
'data' => $visits, 'data' => $visits,
// 'pagination' => [],
] ]
]); ]);
} catch (InvalidArgumentException $e) { } catch (InvalidArgumentException $e) {
@ -59,4 +61,19 @@ class GetVisitsMiddleware extends AbstractRestMiddleware
], 500); ], 500);
} }
} }
/**
* @param Request $request
* @param $key
* @return \DateTime|null
*/
protected function getDateQueryParam(Request $request, $key)
{
$query = $request->getQueryParams();
if (! isset($query[$key]) || empty($query[$key])) {
return null;
}
return new \DateTime($query[$key]);
}
} }