Skip to content

Commit

Permalink
Merge pull request #550 from hngprojects/dev
Browse files Browse the repository at this point in the history
Update staging
  • Loading branch information
timiajayi authored Aug 24, 2024
2 parents 1136ba2 + 63ccd58 commit ac2f167
Show file tree
Hide file tree
Showing 30 changed files with 1,502 additions and 929 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';
}
}
}
28 changes: 12 additions & 16 deletions app/Http/Controllers/Api/V1/Admin/FaqController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use App\Http\Controllers\Controller;
use App\Models\Faq;
use App\Models\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
Expand All @@ -25,21 +26,21 @@ public function store(Request $request)
'question' => $validatedData['question'],
'answer' => $validatedData['answer'],
'category' => $validatedData['category'],
// 'role' => Role::USER,
]);

return response()->json([
'status_code' => 201,
'message' => 'FAQ created successfully',
// 'message' => 'FAQ created successfully',
'success' => true,
'data' => $faq
], 201);

} catch (ValidationException $e) {
return response()->json([
'status_code' => 422,
'message' => 'Validation failed',
'data' => $e->errors()
], 422);

} catch (Exception $e) {
return response()->json([
'status_code' => 500,
Expand All @@ -50,7 +51,7 @@ public function store(Request $request)
}


public function index()
public function index()
{
try {
$faqs = Faq::all()->map(function ($faq) {
Expand All @@ -63,13 +64,12 @@ public function index()
'category' => $faq->category,
];
});

return response()->json([
'status_code' => 200,
'message' => 'Faq fetched successfully',
'data' => $faqs
], 200);

} catch (Exception $e) {
return response()->json([
'status_code' => 500,
Expand All @@ -78,7 +78,7 @@ public function index()
], 500);
}
}

public function update(Request $request, $id)
{
try {
Expand All @@ -87,15 +87,15 @@ public function update(Request $request, $id)
'answer' => 'required|string',
'category' => 'required|string',
]);

$faq = Faq::findOrFail($id);

$faq->update([
'question' => $validatedData['question'],
'answer' => $validatedData['answer'],
'category' => $validatedData['category'],
]);

return response()->json([
'status_code' => 200,
'message' => 'FAQ updated successfully',
Expand All @@ -108,14 +108,12 @@ public function update(Request $request, $id)
'updated_at' => $faq->updated_at->toIso8601String(),
]
], 200);

} catch (ValidationException $e) {
return response()->json([
'status_code' => 422,
'message' => 'Validation failed',
'data' => $e->errors()
], 422);

} catch (Exception $e) {
return response()->json([
'status_code' => 500,
Expand All @@ -125,17 +123,16 @@ public function update(Request $request, $id)
}
}

public function destroy($id)
public function destroy($id)
{
try {
$faq = Faq::findOrFail($id);
$faq->delete();

return response()->json([
'status_code' => 200,
'message' => 'FAQ successfully deleted'
], 200);

} catch (Exception $e) {
return response()->json([
'status_code' => 500,
Expand All @@ -144,5 +141,4 @@ public function destroy($id)
], 500);
}
}

}
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';
}
}
}
27 changes: 12 additions & 15 deletions app/Http/Controllers/Api/V1/Auth/AuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@

class AuthController extends Controller
{
public function __construct(public OrganisationService $organisationService)
{
}
public function __construct(public OrganisationService $organisationService) {}

public function store(Request $request)
{
Expand All @@ -28,48 +26,48 @@ public function store(Request $request)
'email' => 'required|string|email:rfc|max:255|unique:users',
'password' => 'required|string|min:6',
]);

if ($validator->fails()) {
return response()->json([
'status_code' => 422,
'message' => 'Validation error',
'errors' => $validator->errors(),
], 422);
}

try {
DB::beginTransaction();

$user = User::create([
'id' => Str::uuid(),
'email' => $request->email,
'password' => Hash::make($request->password),
'role' => 'user',
'is_verified' => 1,
]);

$user->profile()->create([
'first_name' => $request->first_name,
'last_name' => $request->last_name,
]);

$name = $request->first_name . "'s Organisation";
$organisation = $this->organisationService->create($user, $name);

$role = $user->roles()->create([
'name' => 'admin',
'org_id' => $organisation->org_id,
]);

DB::table('users_roles')->insert([
'user_id' => $user->id,
'role_id' => $role->id,
]);

$token = JWTAuth::fromUser($user);

$is_superadmin = in_array($user->role, ['admin']);

DB::commit();

$email_template_id = null;
Expand All @@ -78,7 +76,7 @@ public function store(Request $request)
if ($emailTemplate) {
$email_template_id = $emailTemplate->id;
}

return response()->json([
'status_code' => 201,
'message' => 'User Created Successfully',
Expand Down Expand Up @@ -112,5 +110,4 @@ public function store(Request $request)
], 500);
}
}

}
Loading

0 comments on commit ac2f167

Please sign in to comment.