Created
September 17, 2021 17:37
-
-
Save Ghostscypher/bcc0981fa8840eba55896c554eed60b0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Middleware; | |
use App\Traits\LockEventTrait; | |
use Closure; | |
use Illuminate\Http\Request; | |
class LockRouteMiddleware | |
{ | |
use LockEventTrait; | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param Closure $next | |
* @param string $key | |
* @param int $seconds | |
* @param bool $unlock_after_request | |
* @param bool $unlock_on_error | |
* @return mixed | |
* @throws \Throwable | |
*/ | |
public function handle(Request $request, Closure $next, string $key, int $seconds = 200, | |
bool $unlock_after_request = true, bool $unlock_on_error = true) | |
{ | |
// Get unique key | |
$key = $this->getKey($key); | |
if($this->isLocked($key)) { | |
abort(419, 'Another request is being processed, please wait and try again in a few seconds.'); | |
} | |
// Lock before executing the request | |
$this->lock($key, $seconds); | |
try{ | |
$response = $next($request); | |
if($unlock_after_request){ | |
$this->unlock($key); | |
} | |
return $response; | |
} catch (\Throwable $th){ | |
if($unlock_on_error){ | |
$this->unlock($key); | |
} | |
// Rethrow the error | |
throw $th; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment