Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cleaned up API and added caching #437

Merged
merged 1 commit into from
Jan 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

* [PR-437](https://github.com/itk-dev/hoeringsportal/pull/437)
Cleaned up API and added caching
* [PR-435](https://github.com/itk-dev/hoeringsportal/pull/435)
Add usable config values for oidc
Update OIDC documentation
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,46 +2,31 @@

namespace Drupal\hoeringsportal_data\Controller\Api;

use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\hoeringsportal_data\Helper\GeoJsonHelper;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Serializer;

/**
* Api controller.
*/
abstract class ApiController extends ControllerBase {

/**
* The request stack.
*
* @var \Symfony\Component\HttpFoundation\RequestStack
*/
protected RequestStack $requestStack;

/**
* Helper.
*
* @var \Drupal\hoeringsportal_data\Helper\GeoJsonHelper
*/
private GeoJsonHelper $geoJsonHelper;

/**
* The serializer.
*
* @var \Symfony\Component\Serializer\Serializer
*/
protected Serializer $serializer;

/**
* Constructor.
*/
final public function __construct(RequestStack $requestStack, GeoJsonHelper $geoJsonHelper, Serializer $serializer) {
$this->requestStack = $requestStack;
$this->geoJsonHelper = $geoJsonHelper;
$this->serializer = $serializer;
final public function __construct(
protected readonly RequestStack $requestStack,
protected readonly RouteMatchInterface $routeMatch,
protected readonly GeoJsonHelper $geoJsonHelper,
protected readonly Serializer $serializer,
) {
}

/**
Expand All @@ -50,6 +35,7 @@ final public function __construct(RequestStack $requestStack, GeoJsonHelper $geo
public static function create(ContainerInterface $container) {
return new static(
$container->get('request_stack'),
$container->get('current_route_match'),
$container->get('hoeringsportal_data.geojson_helper'),
$container->get('serializer')
);
Expand Down Expand Up @@ -79,13 +65,49 @@ protected function generateUrl($name, $parameters = [], $options = []) {
/**
* Create a GeoJSON response.
*/
protected function createGeoJsonResponse(array $features, string $type = 'FeatureCollection') {
$response = new JsonResponse([
'features' => $features,
'type' => 'FeatureCollection',
protected function createGeoJsonResponse(array $features, string $type = 'FeatureCollection', ?array $cacheContexts = NULL, ?array $cacheTags = NULL): CacheableJsonResponse {
$response = new CacheableJsonResponse([
'features' => array_values(
array_filter(
$features,
static fn (array $item) => isset($item['geometry'])
)
),
'type' => $type,
]);
$response->headers->set('content-type', 'application/geo+json');

if ($cacheContexts || $cacheTags) {
// @see https://www.drupal.org/docs/drupal-apis/cache-api/cache-tags#s-what
$response->addCacheableDependency(
(new CacheableMetadata())
// @see https://www.drupal.org/docs/drupal-apis/cache-api/cache-contexts
->setCacheContexts($cacheContexts ?? [])
->setCacheMaxAge(Cache::PERMANENT)
->setCacheTags($cacheTags ?? [])
);
}

return $response;
}

/**
* Adds rels to response.
*
* @see https://datatracker.ietf.org/doc/html/rfc8288
*/
protected function addRels(Response $response, int $page, bool $hasNext): Response {
$routeName = $this->routeMatch->getRouteName();
$rels['self'] = $this->generateUrl($routeName, ['page' => $page]);
if ($page > 1) {
$rels['prev'] = $this->generateUrl($routeName, ['page' => $page - 1]);
}
if ($hasNext) {
$rels['next'] = $this->generateUrl($routeName, ['page' => $page + 1]);
}
$links = array_map(static fn (string $rel, string $url) => sprintf('<%s>; rel="%s"', $url, $rel), array_keys($rels), array_values($rels));
$response->headers->add(['link' => implode(', ', $links)]);

return $response;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,12 @@ public function index() {
}

$entities = $this->helper()->getHearings($conditions);
$features = array_map($this->helper()->serializeGeoJsonHearing(...), $entities);

$features = array_values(array_map([$this->helper(), 'serializeGeoJsonHearing'], $entities));
$response = $this->createGeoJsonResponse($features, 'FeatureCollection');

return $response;
return $this->createGeoJsonResponse(
$features,
cacheTags: ['node_list:hearing'],
);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,12 @@ class PublicMeetingController extends ApiController {
*/
public function dates() {
$entities = $this->getDates();
$features = array_values(array_map([$this->helper(), 'serializeGeoJsonPublicMeetingDate'], $entities));
$features = array_map($this->helper()->serializeGeoJsonPublicMeetingDate(...), $entities);

return $this->createGeoJsonResponse($features);
return $this->createGeoJsonResponse(
$features,
cacheTags: ['node_list:public_meeting'],
);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,24 +31,19 @@ public function index() {
}

// We get one more entity that actually needed to check if we have a "next" relation.
$entities = $this->helper()->getHearings($conditions, ['created' => 'DESC'], $pageSize+1, $pageSize *($page-1));
$entities = $this->helper()->getHearings($conditions, ['created' => 'DESC'], $pageSize + 1, $pageSize * ($page - 1));
$hasNext = count($entities) > $pageSize;
array_pop($entities);
$entities = array_slice($entities, 0, $pageSize);

$features = array_values(array_map([$this->helper(), 'serializeGeoJsonHearing'], $entities));
$response = $this->createGeoJsonResponse($features, 'FeatureCollection');
$features = array_map($this->helper()->serializeGeoJsonHearing(...), $entities);
$response = $this->createGeoJsonResponse(
$features,
cacheContexts: ['url.query_args:geometry', 'url.query_args:page', 'url.query_args:page_size'],
cacheTags: ['node_list:hearing'],
);

// @see https://datatracker.ietf.org/doc/html/rfc8288
$rels['self'] = $this->generateUrl('hoeringsportal_data.api_geojson_v2_hearings', ['page' => $page]);
if ($page > 1) {
$rels['prev'] = $this->generateUrl('hoeringsportal_data.api_geojson_v2_hearings', ['page' => $page-1]);
}
if ($hasNext) {
$rels['next'] = $this->generateUrl('hoeringsportal_data.api_geojson_v2_hearings', ['page' => $page + 1]);
}
$links = array_map(function ($rel, $url) { return sprintf('<%s>; rel="%s"', $url, $rel); }, array_keys($rels), array_values($rels));
$response->headers->add(['link' => implode(', ', $links)]);
$this->addRels($response, $page, $hasNext);

return $response;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,7 @@ public function serializeGeoJsonHearing(NodeInterface $hearing) {

$geometryType = $this->getGeometryType($hearing);

$data = [
'properties' => [
$properties = [
'hearing_id' => (int) $hearing->id(),
'hearing_title' => $hearing->getTitle(),
'hearing_content_state' => $hearing->get('field_content_state')->value,
Expand Down Expand Up @@ -189,11 +188,18 @@ public function serializeGeoJsonHearing(NodeInterface $hearing) {
'hearing_local_plan_ids' => array_map(function ($lokalplan) {
return (int) $lokalplan->id;
}, $lokalplaner),
],
];

// Additional properties for Septima widget.
$properties['start_date'] = $properties['hearing_start_date'];
$properties['end_date'] = $properties['hearing_reply_deadline'];

$data = [
'properties' => $properties,
];

$geometry = $this->getGeometry($hearing);
if (NULL !== $geometry) {
if (isset($geometry['geometry'])) {
$data['geometry'] = $geometry['geometry'];
$data['type'] = 'Feature';
}
Expand Down Expand Up @@ -244,6 +250,10 @@ public function serializeGeoJsonPublicMeetingDate(object $date) {
'date_spots' => (int) $data->spots,
];

// Additional properties for Septima widget.
$properties['start_date'] = $properties['date_time_from'];
$properties['end_date'] = $properties['date_time_to'];

if (isset($data->data->coordinates)) {
$serialized['geometry'] = [
'type' => 'Point',
Expand Down
Loading