2016-11-28 139 views
2

我在Laravel 5.3中構建了一個API。在我routes/api.php文件我有3個端點:重定向Laravel中的路由5.3

Route::post('/notify/v1/notifications', 'Api\Notify\v1\[email protected]'); 

Route::post('/notify/v1/alerts', 'Api\Notify\v1\[email protected]'); 

Route::post('/notify/v1/incidents', 'Api\Notify\v1\[email protected]'); 

一些服務將直接然而調用這些路線,當請求從一些服務到來時,輸入的數據需要經過處理之後才能打到這些端點。

例如,如果來自JIRA的請求,我需要在輸入到達這些端點之前處理輸入。

林認爲要做到這一點最簡單的方法是將有一個四端點就像下面:

Route::post('/notify/v1/jira', 'Api\Notify\v1\[email protected]'); 

的想法是打/notify/v1/jira終點,有formatJiraPost方法過程中的輸入,然後向前根據需要請求/notify/v1/notifications (/alerts, /incidents)

我該如何讓/notify/v1/jira端點將請求轉發到/notify/v1/notifications端點?

您是否看到了更好的方法來做到這一點?

+2

您可以使用中間件格式化您的請求數據,然後將其轉發到同一端點,而不需要第四個請求數據。 – TheFallen

+0

同意@TheFallen。使用中間件來檢查「預處理要求」可能是更好的選擇。儘管需要考慮的一件事是將所有3個端點封裝在中間件內可能會增加一些執行時間開銷。由於「檢查所有請求」以查看是否需要預處理。 – scottevans93

回答

2

根據您的應用程序的工作方式,您可以始終讓您的服務指向/notify/v1/jira,然後按照您的建議進行處理。

另一種方法是讓JIRA服務指向與所有其他服務相同的路由,但使用Before middleware group預處理您的數據。類似於

Route::group(['middleware' => ['verifyService']], function() { 

    Route::post('/notify/v1/notifications', 'Api\Notify\v1\[email protected]'); 

    Route::post('/notify/v1/alerts', 'Api\Notify\v1\[email protected]'); 

    Route::post('/notify/v1/incidents', 'Api\Notify\v1\[email protected]'); 

}); 

您可以在中間件中檢查您的服務。

<?php 

namespace App\Http\Middleware; 

use Closure; 

class verifyService 
{ 

    public function handle($request, Closure $next) 
    { 
     //You could use switch/break case structure 
     if (isJIRA($request)) { 

      //Do some processing, it could be outsourced to another class 
      //$JiraPost = new formatJiraPost($request); 

      //Keep the requesting going to the routes with processed data 
      return $next($request); 
     } 

     //You could add extra logic to check for more services. 

     return $next($request); 
    } 

    protected function isJIRA(Request $request){ 
     //Logic to check if it is JIRA. 
    } 
}