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

Closed
wants to merge 2 commits into from

Conversation

cosmastech
Copy link
Contributor

@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
@rubenvanassche
Copy link
Member

I think we want to keep the amount of properties within people's data objects to the bare minimum so adding another one just for setting a response code seems a lot since it will be included in every data object.

In such a case, why not create a trait which overwrites calculateResponseStatus with a 403?

@cosmastech
Copy link
Contributor Author

cosmastech commented Jan 17, 2025

I think we want to keep the amount of properties within people's data objects to the bare minimum so adding another one just for setting a response code seems a lot since it will be included in every data object.

No worries, I can understand not wanting the package to expand for little edge cases. 👍 This package is great and my team (frontend and backend) really appreciates it!

In such a case, why not create a trait which overwrites calculateResponseStatus with a 403?

That's exactly what we have done already. 😃

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.

2 participants