Skip to content

Commit b6de018

Browse files
committed
Construct self link using collection endpoint
1 parent e4e0086 commit b6de018

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

src/Serializer.php

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Closure;
66
use RuntimeException;
7+
use Tobyz\JsonApiServer\Endpoint\Show;
78
use Tobyz\JsonApiServer\Resource\Resource;
89
use Tobyz\JsonApiServer\Schema\Field\Relationship;
910

@@ -51,16 +52,28 @@ private function addToMap(Resource $resource, mixed $model, array $include): arr
5152

5253
$key = $this->key($type = $resource->type(), $id = $resource->getId($model, $context));
5354

54-
$url = "{$context->api->basePath}/$type/$id";
55-
5655
if (!isset($this->map[$key])) {
5756
$this->map[$key] = [
5857
'type' => $type,
5958
'id' => $id,
60-
'links' => [
61-
'self' => $url,
62-
],
6359
];
60+
61+
foreach ($this->context->api->collections as $collection) {
62+
if (!in_array($resource->type(), $collection->resources())) {
63+
continue;
64+
}
65+
66+
foreach ($collection->endpoints() as $endpoint) {
67+
if ($endpoint instanceof Show) {
68+
$this->map[$key]['links']['self'] = implode('/', [
69+
$context->api->basePath,
70+
$collection->name(),
71+
$id,
72+
]);
73+
break;
74+
}
75+
}
76+
}
6477
}
6578

6679
foreach ($this->context->sparseFields($resource) as $field) {

0 commit comments

Comments
 (0)