Skip to content

Commit

Permalink
Merge pull request #549 from Muhammad235/feat/store-api-status-command
Browse files Browse the repository at this point in the history
feat: store API test result data and retrieval endpoint
  • Loading branch information
Dev-Tonia authored Aug 24, 2024
2 parents bcc0e4e + 59d9954 commit 63ccd58
Show file tree
Hide file tree
Showing 5 changed files with 151 additions and 76 deletions.
90 changes: 90 additions & 0 deletions app/Console/Commands/StoreApiStatus.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?php

namespace App\Console\Commands;

use DateTime;
use DateTimeZone;
use Illuminate\Console\Command;

class StoreApiStatus extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'store:api-status';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Get test result from result.json file and save to the database';

/**
* Execute the console command.
*/
public function handle()
{

// Get test result from json file
$data = file_get_contents(base_path('../result.json'));

$data = json_decode($data, true);

// Get the collections and executions arrays from the data
$collections = $data['collection']['item'];
$executions = $data['run']['executions'];

// Loop through each collection
foreach ($collections as $collectionIndex => $collection) {

// Loop through each item within the current collection and match it with the corresponding execution
foreach ($collection['item'] as $itemIndex => $item) {

$execution = $executions[$itemIndex] ?? null;
$status = null;
$response_time = null;

if ($execution && isset($execution['assertions']) && is_array($execution['assertions'])) {
// Extract the first assertion and response time if available
$assertions = $execution['assertions'];
$status = $assertions[0]['assertion'] ?? null;
$response_time = $execution['response']['responseTime'] ?? null;
}

// Get the current date and time
$date = new DateTime("now", new DateTimeZone('Africa/Lagos'));
$last_checked = $date->format('Y-m-d h:i A');

// Update the api status record
\App\Models\ApiStatus::updateOrCreate(['api_group' => $item['name']], [
'api_group' => $item['name'],
'method' => $item['request']['method'],
'status' => $status,
'response_time' => $response_time,
'last_checked' => $last_checked,
'details' => $this->getDetails($execution),
]);
}
}

$this->info('Api status stored successfully');
}


private function getDetails($execution)
{
$response_code = $execution['response']['code'] ?? null;
$response_time = $execution['response']['responseTime'] ?? null;

if ($response_code >= 500 || $response_code === null) {
return 'API not responding (HTTP ' . ($response_code ?? 'Unknown') . ')';
} elseif ($response_time > 400) {
return 'High response time detected';
} else {
return 'All tests passed';
}
}
}
81 changes: 6 additions & 75 deletions app/Http/Controllers/Api/V1/ApiStatusCheckerController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,91 +2,22 @@

namespace App\Http\Controllers\Api\V1;

use DateTime;
use DateTimeZone;
use Illuminate\Http\Request;
use App\Models\ApiStatus;
use App\Http\Controllers\Controller;


class ApiStatusCheckerController extends Controller
{

public function status()
public function index()
{
// Load and decode the JSON file
$data = file_get_contents(base_path('../result.json'));
// $data = file_get_contents('https://staging.api-php.boilerplate.hng.tech/storage/result.json');
$api_statuses = ApiStatus::all();

$data = json_decode($data, true);

// Get the collections and executions arrays from the data
$collections = $data['collection']['item'];
$executions = $data['run']['executions'];

// Initialize an array to hold the results
$responseArray = [];

// Loop through each collection
foreach ($collections as $collectionIndex => $collection) {

// Loop through each item within the current collection
foreach ($collection['item'] as $itemIndex => $item) {

$status = null;
$response_time = null;

if (isset($executions[$itemIndex])) {
$execution = $executions[$itemIndex];

// Check if assertions key exists
if (isset($execution['assertions']) && is_array($execution['assertions'])) {
$assertions = $execution['assertions'];


// Loop through each assertion and extract relevant data
foreach ($assertions as $index => $assertion) {
if ($index === 0) {
$status = $assertion['assertion'];
} elseif ($index === 1) {
$response_time = $execution['response']['responseTime'];
}
}
}
}

$date = new DateTime("now", new DateTimeZone('Africa/Lagos'));
$formattedDate = $date->format('Y-m-d h:i A');

// Append only the name and execution_data to the response array
$responseArray[] = [
'api_group' => $item['name'],
'method' => $item['request']['method'],
'status' => $status,
'response_time' => $response_time,
'last_checked' => $formattedDate,
'details' => $this->getDetails($execution)
];
}
}

// Return the accumulated results as a JSON response
return response()->json([
'data' => $responseArray
'status_code' => 200,
'message' => 'Api status data returned successfully',
'data' => $api_statuses
]);
}


private function getDetails($execution)
{
$response_code = $execution['response']['code'] ?? null;
$response_time = $execution['response']['responseTime'] ?? null;

if ($response_code >= 500 || $response_code === null) {
return 'API not responding (HTTP ' . ($response_code ?? 'Unknown') . ')';
} elseif ($response_time > 400) {
return 'High response time detected';
} else {
return 'All tests passed';
}
}
}
21 changes: 21 additions & 0 deletions app/Models/ApiStatus.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class ApiStatus extends Model
{
use HasFactory, HasUuids;

protected $fillable = [
'api_group',
'method',
'status',
'response_time',
'last_checked',
'details'
];
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('api_statuses', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('api_group')->nullable();
$table->string('method')->nullable();
$table->string('status')->nullable();
$table->string('response_time')->nullable();
$table->string('last_checked')->timestamps();
$table->string('details')->nullable();
$table->timestamps();
});
}

/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('api_statuses');
}
};
2 changes: 1 addition & 1 deletion routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@
return 'Language Learning AI Game Version 1';
});

Route::get('/api-status', [ApiStatusCheckerController::class, 'status']);
Route::get('/api-status', [ApiStatusCheckerController::class, 'index']);

Route::post('/auth/register', [AuthController::class, 'store']);
Route::post('/auth/login', [LoginController::class, 'login']);
Expand Down

0 comments on commit 63ccd58

Please sign in to comment.