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

Add ability to set responseStatusCode on Response objects #891

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

cosmastech
Copy link

@cosmastech cosmastech commented Oct 19, 2024

Goal

Provide the ability to set a specific status code on responses.

Background

I'm using the package for error response messages (rather than throwing exceptions). For instance, we have a custom NotAuthorizedResponse that will have a payload like this:

{
    "code": "not_authorized",
    "uuid": "abcd-e4gab2-ffff-a324-0001",
    "message": "You are not authorized to view this post"
}

And an object like this:

class NotAuthorizedResponse extends Response
{
    public ErrorResponseEnum $code = ErrorResponseEnum::NOT_AUTHORIZED;

    public function __construct(
        public ?string $uuid,
        public string $message = "We could not find this resource"
    ) {}
}

We can get away with overriding the calculateResponseStatus method in a BaseResponse class, but I thought that this functionality would be helpful for others as well.

Usage

public function show(Request $request): PostResponse|NotAuthorizedResponse
{
    if (! $request->user()->isAdmin()) {
        return (new NotAuthorizedResponse($request->uuid, "You are not authorized to view this post"))
            ->setResponseStatusCode(403);
    }
   // ... happy path
}

@cosmastech cosmastech marked this pull request as ready for review October 20, 2024 11:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant