Skip to content

Commit 6837828

Browse files
committed
Enhance API response handling by inferring status codes for Post and Delete routes
1 parent 5ac643a commit 6837828

2 files changed

Lines changed: 9 additions & 5 deletions

File tree

src/Controller/Decorator/ApiResponseDecorator.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
namespace OpenSolid\Api\Controller\Decorator;
66

77
use OpenSolid\Api\Controller\Model\ResponseOptions;
8+
use OpenSolid\Api\Routing\Attribute\Delete;
9+
use OpenSolid\Api\Routing\Attribute\Post;
810
use OpenSolid\CallableInvoker\CallableMetadata;
911
use OpenSolid\CallableInvoker\Decorator\CallableClosure;
1012
use Symfony\Component\HttpFoundation\JsonResponse;
@@ -39,10 +41,15 @@ public function decorate(CallableClosure $callable, CallableMetadata $metadata):
3941
$request = $metadata->context['request'];
4042
/** @var Type $returnType */
4143
$type ??= $metadata->getAttribute('return_type');
44+
$statusCode ??= $request->attributes->getInt('_api_status_code', match ($request->attributes->getInt('_api_route_class')) {
45+
Post::class => 201,
46+
Delete::class => 204,
47+
default => 200,
48+
});
4249

4350
return new StreamedResponse(
4451
callbackOrChunks: $this->jsonStreamWriter->write($response, $type),
45-
status: $statusCode ?? $request->attributes->getInt('_api_status_code', 200),
52+
status: $statusCode,
4653
headers: $headers ?? ['Content-Type' => 'application/json'],
4754
);
4855
}

src/Routing/Attribute/ApiRoute.php

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,17 +28,14 @@ public function __construct(
2828
public array $tags = [],
2929
public bool $deprecated = false,
3030
) {
31-
if (null === $statusCode && $this instanceof Post) {
32-
$statusCode = 201;
33-
}
34-
3531
parent::__construct(
3632
path: $path,
3733
name: $name,
3834
requirements: $requirements,
3935
options: $options,
4036
defaults: $defaults + array_filter([
4137
'_api_controller' => true,
38+
'_api_route_class' => $this::class,
4239
'_api_status_code' => $statusCode,
4340
], fn ($v) => null !== $v),
4441
host: $host,

0 commit comments

Comments
 (0)