refactor(private-key-update): implement transaction for private key association and connection validation
- Refactored the private key update logic to use a database transaction for associating the private key with the server, ensuring atomicity. - Improved error handling by refreshing the server state upon failure and validating the connection after updates. - Enhanced success and error dispatching for better user feedback during the update process.
This commit is contained in:
@@ -5,6 +5,7 @@ namespace App\Livewire\Server\PrivateKey;
|
|||||||
use App\Models\PrivateKey;
|
use App\Models\PrivateKey;
|
||||||
use App\Models\Server;
|
use App\Models\Server;
|
||||||
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
|
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
use Livewire\Component;
|
use Livewire\Component;
|
||||||
|
|
||||||
class Show extends Component
|
class Show extends Component
|
||||||
@@ -35,19 +36,19 @@ class Show extends Component
|
|||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
$originalPrivateKeyId = $this->server->getOriginal('private_key_id');
|
|
||||||
try {
|
try {
|
||||||
$this->authorize('update', $this->server);
|
$this->authorize('update', $this->server);
|
||||||
$this->server->update(['private_key_id' => $privateKeyId]);
|
DB::transaction(function () use ($ownedPrivateKey) {
|
||||||
['uptime' => $uptime, 'error' => $error] = $this->server->validateConnection(justCheckingNewKey: true);
|
$this->server->privateKey()->associate($ownedPrivateKey);
|
||||||
if ($uptime) {
|
$this->server->save();
|
||||||
$this->dispatch('success', 'Private key updated successfully.');
|
['uptime' => $uptime, 'error' => $error] = $this->server->validateConnection(justCheckingNewKey: true);
|
||||||
} else {
|
if (! $uptime) {
|
||||||
throw new \Exception($error);
|
throw new \Exception($error);
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
$this->dispatch('success', 'Private key updated successfully.');
|
||||||
} catch (\Exception $e) {
|
} catch (\Exception $e) {
|
||||||
$this->server->update(['private_key_id' => $originalPrivateKeyId]);
|
$this->server->refresh();
|
||||||
$this->server->validateConnection();
|
$this->server->validateConnection();
|
||||||
$this->dispatch('error', $e->getMessage());
|
$this->dispatch('error', $e->getMessage());
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user