從零開始系列-Laravel編寫api服務介面:2.Dingo封裝

lixueyuan發表於2021-05-12

前言

文件:《Dingo API 3.x 中文文件》
不用 dingo 完全可以滿足所有需求,但是用了 dingo 更方便,特別是 transformer 和一些函式非常好用,下面簡單介紹一下安裝和使用,注意:Laravel 新版可以不用dingo,直接用 resource 替代,具體可見文件 Eloquent: API 資源

  1. 安裝
    最新版本為dingo3.0.0

composer require dingo/api

  1. 複製配置檔案

php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"

  1. 複製到.env檔案下
    # dingo
    API_STANDARDS_TREE=prs # The personal tree (prs) is primarily meant for projects that are not distributed commerically.
    API_SUBTYPE=homestead # Your subtype is typically a short name of your application or project, all lowercase.You can configure this in your .env file. 
    API_PREFIX=api # If you've ever worked with an API you'll know that most are served from either a subdomain or under a prefix. A prefix or subdomain is required, but only one. Avoid putting a version number as your prefix or subdomain as versioning is handled via the Accept header.
    API_VERSION=v1 # This version is the default version of your API and is used as a fallback in several circumstances whenever a version is not supplied. This version is also used
    API_DEBUG=true 
  2. 以下程式碼複製到 app/Providers/AppServiceProvider的 boot 方法裡面
$this->app['Dingo\Api\Transformer\Factory']->setAdapter(function ($app) {
            $fractal = new \League\Fractal\Manager;
            $fractal->setSerializer(new \League\Fractal\Serializer\JsonApiSerializer); // 設定響應器(new ArraySerializer();)
            return new \Dingo\Api\Transformer\Adapter\Fractal($fractal);
});

5.路由如:

// laravel 預設路由
Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

if ('local' === config('app.env')) {
    Route::any('sms', '\\Toplan\\Sms\\SmsController@getInfo');
}
// 配置dingo路由
$api = app('Dingo\Api\Routing\Router');
// 預設Accept application/prs.hospital.v1+json
$api->version('v1', ['namespace' => 'App\Http\Controllers\Api', 'middleware' => ['bindings']], function ($api) {
    //後臺介面
    $api->group(['as' => 'admin', 'prefix' => 'admin', 'namespace' => 'Admin', 'middleware' => []], function ($api) {
        // 登入獲取token
        $api->post('authorizations', 'AuthorizationsController@store')
            ->name('.authorizations.store');
        // 重新整理生成新的token
        $api->get('refresh_token', 'AuthorizationsController@refresh')
            ->name('.authorizations.refresh');
        // 退出登入
        $api->get('log_out', 'AuthorizationsController@logOut')->name('.authorizations.logout');
        //需要登入後的介面
        $api->group(['middleware' => ['auth:admin', 'bindings']], function ($api) {

        });
    }
});

6.攔截dingo異常 例如:


API::error(function (ValidationException $exception) {
            $errors = $exception->errors();
            return response()->json(['message' => $errors->first(), 'status_code' => 422], 422);
        });
API::error(function (BadRequestException $exception) {
    $errors = $exception->getMessage();
    return response()->json(['data' => $exception->data, 'message' => $errors, 'status_code' => 422], 422);
});
// dingo 表單驗證自定義異常
API::error(function (ValidationHttpException $exception) {
    $errors = $exception->getErrors();
    return response()->json(['message' => $errors->first(), 'status_code' => 422], 422);
});
API::error(function (InvalidRequestException $exception) {
    return response()->json(['message' => $exception->getMessage(), 'status_code' => 422], 422);
});
API::error(function (\InvalidArgumentException $exception) {
    return response()->json(['message' => $exception->getMessage(), 'status_code' => 422], 422);
});

API::error(function (ModelNotFoundException $e) {
    $data = config('app.debug') ? [
        'message'   => $e->getMessage(),
        'exception' => get_class($e),
        'file'      => $e->getFile(),
        'line'      => $e->getLine(),
        'trace'     => collect($e->getTrace())->map(function ($trace) {
            return Arr::except($trace, ['args']);
        })->all(),
    ] : ['message' => '資源未找到'];
    return response()->json($data, 422);
});
本作品採用《CC 協議》,轉載必須註明作者和本文連結
程式設計兩年半,喜歡ctrl(唱、跳、rap、籃球)

相關文章