dingo API 自定义数据响应格式?

配置文件中有 错误格式的定义

'errorFormat' => [
        'message'     => ':message',
        'errors'      => ':errors',
        'code'        => ':code',
        'status_code' => ':status_code',
        'debug'       => ':debug',
    ],

数据正常响应时有没有可以配置的地方 配置配置成

'normalCustomFormat' => [
        'message'     => ':message',
        'data'      => ':data',
        'code'        => ':code',
        'status_code' => ':status_code',
    ],
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
最佳答案

你可以通过 return response()->json(array[]) 的方式自定义接口返回的数据。

5年前 评论
讨论数量: 3

你可以通过 return response()->json(array[]) 的方式自定义接口返回的数据。

5年前 评论
xiaopi

不过这个是laravel的返回格式,用过就是不是dingo 风格了吧,

5年前 评论

EventServiceProvider增加如下内容:

protected $listen = [
    // 监听 Dingo API发送响应之前对响应进行转化的事件
    ResponseWasMorphed::class => [
        FormatResponse::class
    ],
];

FormatResponse代码如下:

public function handle(ResponseWasMorphed $event)
{
    $statusCode = $event->response->getStatusCode();
    Log::debug("响应的状态码为:" . $statusCode . ',修改响应格式');

    // 成功时追加响应信息
    if (preg_match("/^2[0-9]{2}$/", $statusCode)) {
        // 取dingo配置文件内的异常时响应格式字段,确保整个响应数据格式一致
        $errorFormat = config('api.errorFormat');
        $errorFormatKey = array_keys($errorFormat);

        // 追加的响应
        $addData = [
            $errorFormatKey[0] => 200, // HTTP响应状态码
            $errorFormatKey[1] => 0, // 自定义状态码
            $errorFormatKey[2] => 'success', // 信息描述
        ];

        $tempContent = [];

        if (is_null($event->content)) {
            $event->content = [];
        }

        // 响应内容
        $tempContent = [
            'data' => isset($event->content['data']) ? $event->content['data'] : $event->content // 解决使用了transform后data重复问题
        ];

        /**
         * 控制器分页举例
         * $histories = DB::table('jpush_message_history')->paginate(3);
         * return $this->response->paginator($histories, new TestTransformer());
         */
        // 分页处理
        if (isset($event->content) && isset($event->content['meta']) && isset($event->content['meta']['pagination'])) {
            Log::debug("对响应的分页数据进行重新组装");
            $tempContent['pageSize'] = $event->content['meta']['pagination']['per_page'];
            $tempContent['total'] = $event->content['meta']['pagination']['total'];
            $tempContent['currentPage'] = $event->content['meta']['pagination']['current_page'];
        }

        $event->content = array_merge($addData, $tempContent);
    }
}
2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!