All good Laravel API & Mockup

Image URL: http://www.cloudways.com/blog/wp-content/uploads/controllers-middleware-laravel-5-4.jpg

My team lead told me, “Bhai (Brother), we need to make this feature ready. But as the mobile team is working parallelly we need to provide them a mockup so that they can work alongside. Can you please do it?”

So, my task is to add a mock-up to the existing endpoints. Being a developer by definition I am a lazy person. Yes, that true. But how can I accomplish the task with the lowest amount of work?

Laravel/Lumen Middleware is the savior…

Yes. In my case, Laravel middleware saved me from doing the extra task. How did I achive so?

  • Created an after middleware that intercepts when the controller returns the response. (middleware code below)
  • Registered that middleware in my LaravelKernel.php or Lumenbootstrap/app.php in routeMiddleware
// ... example below
'with_mockup' => App\Http\Middleware\BackendMockUpMiddleware::class,
// ...
  • Added that middleware to my expected routes where I need to extend the response and send some extra data.
// ... as usual previous routes
$router->get('{orderId:[a-z0-9]+}', [
'middleware' => 'mockup_with:order.show.promo',
'uses' => 'OrderController@show',
]);
// ...
  • And, finally my BackendMockupMiddleware.php
<?php namespace App\Http\Middleware;

use Closure;
use Laravel\Lumen\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class BackendMockUpMiddleware
{
public function handle ($request, Closure $next, $endpoint = '')
{
$response = $next($request);
$expectedMethodName = camel_case(str_replace('.', '_', $endpoint));

// check if endpoint is given or not
// and also, check if method name is available in the class or not.
if (empty($endpoint) || !method_exists($this,
$expectedMethodName)) {
return $response;
}

$original = json_decode($response->getContent(), true);

// first params is the original output array from the controller
// second param is the request object
// third param is a clone of original response object
$extra = $this->$expectedMethodName($original, $request, clone $response);

$response->setContent(json_encode(array_merge($original, $extra)));

return $response;
}
    // order.show.promo
private function orderShowPromo ($original, Request $request, Response $response) {
return $response->getStatusCode() >= 400 ? [] : [
"show_promo_code" => true,
];
}
}

What this code does is, it checks if the mockup middleware applied in an endpoint, and it explicitly mentions any value or not. If endpoint parameter of the handle method has any value then it checks if the camel-cased method exists in the same class or not. If it has the camel-cased method, then it passes the json array, current request and the cloned response object to that method as parameters. It then merges the returned value to the existing controller response and sets to the response.

So, whenever you need to apply some extra data to your actual/original response for mockup, you need to apply that middleware with some explicit parameter and make a camel-case method in the class. Then you're done with your mockup and enjoy your free time.

That’s it. Happy coding. ❤ ✌️