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

Redirect back when an Inertia response is empty (customizable) #350

Merged
merged 2 commits into from
Jan 20, 2022
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
57 changes: 29 additions & 28 deletions src/Middleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Symfony\Component\HttpFoundation\Response;

class Middleware
Expand Down Expand Up @@ -82,57 +83,57 @@ public function handle(Request $request, Closure $next)
});

Inertia::share($this->share($request));

Inertia::setRootView($this->rootView($request));

$response = $next($request);
$response = $this->checkVersion($request, $response);

return $this->changeRedirectCode($request, $response);
if (! $request->header('X-Inertia')) {
return $response;
}

if ($request->method() === 'GET' && $request->header('X-Inertia-Version', '') !== Inertia::getVersion()) {
$response = $this->onVersionChange($request, $response);
}

if ($response->isOk() && empty($response->getContent())) {
$response = $this->onEmptyResponse($request, $response);
}

if ($response->getStatusCode() === 302 && in_array($request->method(), ['PUT', 'PATCH', 'DELETE'])) {
$response->setStatusCode(303);
}

return $response;
}

/**
* In the event that the assets change, initiate a
* client-side location visit to force an update.
* Determines what to do when an Inertia action returned with no response.
* By default, we'll redirect the user back to where they came from.
*
* @param Request $request
* @param Response $response
* @return Response
*/
public function checkVersion(Request $request, Response $response)
public function onEmptyResponse(Request $request, Response $response): Response
{
if ($request->header('X-Inertia') &&
$request->method() === 'GET' &&
$request->header('X-Inertia-Version', '') !== Inertia::getVersion()
) {
if ($request->hasSession()) {
$request->session()->reflash();
}

return Inertia::location($request->fullUrl());
}

return $response;
return Redirect::back();
}

/**
* Changes the status code during redirects, ensuring they are made as
* GET requests, preventing "MethodNotAllowedHttpException" errors.
* Determines what to do when the Inertia asset version has changed.
* By default, we'll initiate a client-side location visit to force an update.
*
* @param Request $request
* @param Response $response
* @return Response
*/
public function changeRedirectCode(Request $request, Response $response)
public function onVersionChange(Request $request, Response $response): Response
{
if ($request->header('X-Inertia') &&
$response->getStatusCode() === 302 &&
in_array($request->method(), ['PUT', 'PATCH', 'DELETE'])
) {
$response->setStatusCode(303);
if ($request->hasSession()) {
$request->session()->reflash();
}

return $response;
return Inertia::location($request->fullUrl());
}

/**
Expand All @@ -142,7 +143,7 @@ public function changeRedirectCode(Request $request, Response $response)
* @param Request $request
* @return object
*/
public function resolveValidationErrors(Request $request)
protected function resolveValidationErrors(Request $request)
{
if (! $request->session()->has('errors')) {
return (object) [];
Expand Down
13 changes: 13 additions & 0 deletions stubs/middleware.stub
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,17 @@ class {{ class }} extends Middleware
//
]);
}

/**
* Determines what to do when an Inertia action returned with no response.
* By default, we'll redirect the user back to where they came from.
*
* @param Request $request
* @param Response $response
* @return Response
*/
public function onEmptyResponse(Request $request, Response $response): Response
{
return parent::onEmptyResponse($request, $response);
}
}
54 changes: 54 additions & 0 deletions tests/MiddlewareTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,60 @@

class MiddlewareTest extends TestCase
{
public function test_no_response_value_by_default_means_automatically_redirecting_back_for_inertia_requests(): void
{
$fooCalled = false;
Route::middleware(Middleware::class)->put('/', function () use (&$fooCalled) {
$fooCalled = true;
});

$response = $this
->from('/foo')
->put('/', [], [
'X-Inertia' => 'true',
'Content-Type' => 'application/json',
]);

$response->assertRedirect('/foo');
$response->assertStatus(303);
$this->assertTrue($fooCalled);
}

public function test_no_response_value_can_be_customized_by_overriding_the_middleware_method(): void
{
Route::middleware(ExampleMiddleware::class)->get('/', function () {
// Do nothing..
});

$this->expectException(\LogicException::class);
$this->expectExceptionMessage('An empty Inertia response was returned.');

$this
->withoutExceptionHandling()
->from('/foo')
->get('/', [
'X-Inertia' => 'true',
'Content-Type' => 'application/json',
]);
}

public function test_no_response_means_no_response_for_non_inertia_requests(): void
{
$fooCalled = false;
Route::middleware(Middleware::class)->put('/', function () use (&$fooCalled) {
$fooCalled = true;
});

$response = $this
->from('/foo')
->put('/', [], [
'Content-Type' => 'application/json',
]);

$response->assertNoContent(200);
$this->assertTrue($fooCalled);
}

public function test_the_version_is_optional(): void
{
$this->prepareMockEndpoint();
Expand Down
14 changes: 14 additions & 0 deletions tests/Stubs/ExampleMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Http\Request;
use Inertia\Middleware;
use Symfony\Component\HttpFoundation\Response;

class ExampleMiddleware extends Middleware
{
Expand Down Expand Up @@ -48,4 +49,17 @@ public function share(Request $request): array
{
return array_merge(parent::share($request), $this->shared);
}

/**
* Determines what to do when an Inertia action returned with no response.
* By default, we'll redirect the user back to where they came from.
*
* @param Request $request
* @param Response $response
* @return Response
*/
public function onEmptyResponse(Request $request, Response $response): Response
{
throw new \LogicException('An empty Inertia response was returned.');
}
}