I recently noticed that my api.php
route file has 500kb length, compared to web.php
which has 30kb. I have more than 100 API endpoints & the API is public.
In every single API endpoint I use the same structure:
try
{
// Do something
}
catch (\Exception $e)
{
\Log::critical($e->getMessage());
return response()->json(['message' => 'Unexpected error..'], 403);
}
None of the endpoints points to a controller, only few endpoints points to a class & returns a value.
A common full example of and endpoint content:
try
{
// Validates if allowed
if (UserIsNotAllowed(....))
return response()->json(['message' => "You don't have rights to access this endpoint"], 403);
// Applies validations
$data = ['description' => $request->description];
$rules =
[
'description' =>
[
'required',
Rule::unique('some_table_sample', 'description')->where(function($query)
{
$query->where('subscription_id', \Auth::user()->subscription_id);
})
],
];
$validator = Validator::make($data, $rules);
if ($validator->fails())
return response()->json(['message' => $validator->errors()->first()], 403);
// Adds to table
$sts = new \App\Models\SomeTableSample;
$sts->subscription_id = \Auth::user()->subscription_id;
$sts->description = $request->description;
$sts->active = $request->active == 'true';
$sts->save();
// Log in DB
(new \App\Classes\Log)->setSubscription(...)
->setUser('...')
->setTableId('...')
->setTableName('...')
->setAction('Created')
->create();
return response()->json(['data' => $sts], 200);
}
catch (\Exception $e)
{
\Log::critical($e->getMessage());
return response()->json(['message' => 'Unexpected error..'], 403);
}
I'm not saying I have noticed any performance issue, but I was wondering if this may lead in the future to some troubles? Should I start thinking about moving all the content of the endpoints towards a controller?
CodePudding user response:
For ease of maintenance it would be worth refactoring. For your future self and other developers, having a well-organised routing/processing architecture will help keep development moving.
As for performance: it likely will, though I'm unsure at what point Laravel will start to slow. Worth doing some profiling as you refactor.