小白折腾服务器(六):使用后置中间件自定义接口成功返回格式

题记

肯定有小伙伴公司团队强制规范api返回code、message、data。
肯定有小伙伴纠结过自定义laravel的分页返回格式,不管是用api资源类还是没用资源类。
肯定有小伙伴是写了公共方法,helpers文件中或base控制器中继承来处理正确数据返回。
肯定有小伙伴公司团队强制要求记录每个接口请求日志、响应日志。

那么,最好的处理位置,一定是中间件啦


更新在最前
2019-11-14更新,我们另一个项目用laravel5.8版本,该后置中间件做了一部分调整:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Pagination\LengthAwarePaginator;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class After
{
    /**
     * 处理成功返回自定义格式
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        if (is_array($response)) {
            return $response;
        }

        // 如果是导出Excel类型直接返回
        if ($response instanceof BinaryFileResponse) {
            return $response;
        }

        // 执行动作
        $oriData = $response->getOriginalContent();
        $content = json_decode($response->getContent(), true) ?? $oriData;
        $content = is_array($oriData) ? $oriData : $content;

        if ($content['code'] ?? 0) {
            return $response;
        }

        $data['data'] = isset($content['data']) ? $content['data'] : $content;

        if ($content['meta'] ?? []) {
            $data['meta'] = [
                'total' => $content['meta']['total'],
                'page'  => $content['meta']['page'] ?? $content['meta']['current_page'] ?? 0,
                'size'  => $content['meta']['size'] ?? $content['meta']['per_page'] ?? 0,
            ];
        }

        if ($oriData instanceof LengthAwarePaginator) {
            $data['meta'] = [
                'total' => $content['total'],
                'page'  => $content['current_page'],
                'size'  => (int)$content['per_page'],
            ];
        }

        if ($data['data']['data'] ?? []) {
            $data['data'] = $data['data']['data'];
        }

        $message  = ['code' => 0, 'message' => 'success', 'data' => []];
        $temp     = ($content) ? array_merge($message, $data) : $message;
        $response = $response instanceof JsonResponse ? $response->setData($temp) : $response->setContent($temp);

        return $response;
    }

以下是原文(laravel5.5)

新建After中间件:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\JsonResponse;

class After
{
    /**
     * 记录响应日志,处理成功返回自定义格式
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        // 执行动作
        if ($response instanceof JsonResponse) {
            $oriData = $response->getData();

            $message = [
                'code'    => 0,
                'message' => 'success',
            ];

            $data['data'] = ($oriData->data ?? []) ? $oriData->data : $oriData;

            if ($oriData->current_page ?? '') {
                $data['meta'] = [
                    'total'        => $oriData->total ?? 0,
                    'per_page'     => (int)$oriData->per_page ?? 0,
                    'current_page' => $oriData->current_page ?? 0,
                    'last_page'    => $oriData->last_page ?? 0
                ];
            }

            if ($oriData->meta ?? '') {
                $data['meta'] = [
                    'total'        => $oriData->meta->total ?? 0,
                    'per_page'     => (int)$oriData->meta->per_page ?? 0,
                    'current_page' => $oriData->meta->current_page ?? 0,
                    'last_page'    => $oriData->meta->last_page ?? 0
                ];
            }

            $temp = ($oriData) ? array_merge($message, $data) : $message;

            $response = $response->setData($temp);
            iuLog('debug', 'Response Success: ', $response->getData());
            iuLog(PHP_EOL);
        }

        return $response;
    }
}

效果:

最基础的返回详情:
    public function show(Topic $topic)
    {
        return $topic;
    }

file

最基础的返回分页:
    public function index(Request $request, Topic $topic)
    {
        // 为了截图完整 只查 id 和 title 
        return $topic->paginate($request->per_page ?? 15, ['id', 'title']);
    }

file

使用API资源类的返回详情:
    public function show(Product $product)
    {
        return new ProductResource($product);
    }

file

使用API资源类的返回分页:
    public function index(Request $request, Product $product)
    {
        $list = $product->paginate($request->per_page ?? 15);

        // 这里把ProductResource的toArray()改了,为了截图只保留 id 和 title 

        return ProductResource::collection($list);
    }

file

最基础的只返回操作成功:
    public function update(Product $product)
    {
        return [];
    }

返回格式:空数组就ok啦
file

后记

我之前用的是在helpers函数中新建success(),successPaginate()等方法,使用API资源的时候,helpers中新建getPaginateMeta()方法,然后使用API资源类的additional()方法。
api资源分页的返回姿势是这样的

 $list = User::paginate($request->per_page ?? 15);

 return UserResource::collection(collect($list->items()))
            ->additional(getPaginateMeta($list));

这里的笔记是,很多人想要获得laravel分页的data(就是不包括link,meta这些数据的主数据),其实$list->items()就是了。
如果使用这些自定义辅助函数,我需要给多个辅助函数增加['code' => 0, 'message' => 'success'] ,给多个辅助函数增加记录日志的地方,而且自定义的辅助方法记日志好加,但api资源返回的日志就不好加了....

看下日志:iu.test 是本地环境啦,线上也ok的
file

本作品采用《CC 协议》,转载必须注明作者和本文链接
本帖由系统于 5年前 自动加精
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 26

错误信息如何处理?

5年前 评论

厉害了我的哥

5年前 评论

@等车的猪 @等车的猪 一枚小白的尝试记录和总结 :sweat_smile:

5年前 评论

是不是在路由上进行指定中间件?

5年前 评论

@mingzaily 不是,全局中间件在 app/Http/Kernel.php 中添加。
像我比较懒,就是这样写:

 protected $middlewareGroups = [
        'web' => [
            ···
            Access::class,
            After::class
        ],

        'api' => [
            Access::class,
            After::class,
            'throttle:60,1',
            'bindings',
        ],
    ];

    protected $routeMiddleware = [
       ···
        'access'        => Access::class,
        'after'         => After::class
    ];
5年前 评论

学写了, 感谢

5年前 评论

Resource 里面有一个 $with 和 $appends 可以满足需求.

5年前 评论

@DamonTo 并不是每个接口都会走resource

5年前 评论

@aen233

"message": "Call to undefined function iulog()", "exception": "Symfony\Component\Debug\Exception\FatalThrowableError",
"file": "F:\Laravel\app\Http\Middleware\API\After.php",
"line": 53,

我看了下代码

iuLog('debug', 'Response Success: ', $response->getData());
iuLog(PHP_EOL);

4年前 评论

iuLog见这里小白折腾服务器(五):自己写个记录日志的小方法,解决使用 supervisor 后日志堆叠
如果不使用supervisor的话,可以把这两行改成Log::debug('Response Success: ', $response->getData());就ok了

4年前 评论

@汪阿浠 主要是我学艺不精,没找到supervisor 日志解决堆叠的正确姿势- -

4年前 评论

@aen233 666啊,我是前天才开始接触Laravel的,你的教程已经给我醍醐灌顶了! :blush: 非常感谢!

4年前 评论

@aen233 我感觉全局中间件放在

protected $middleware = [
...
\App\Http\Middleware\After::class
];

会不会更加好?

4年前 评论

@汪阿浠 可以的,写在路由组里也是因为新起的中间件,谨慎起见

4年前 评论

@aen233 对了请教下,既然是自定义的返回方法,那么执行时候如何自定义“code“和“message”的返回信息呢?

4年前 评论

@汪阿浠 在中间件的handle方法里

 public function handle($request, Closure $next)
    {
        $response = $next($request);

        // 执行动作
        if ($response instanceof JsonResponse) {
            $oriData = $response->getData();

            // 这里的code和message就是自定义的啊,你可以改成任何你想要的返回值
            $message = [
                'code'    => 0,
                'message' => 'success',
            ];
4年前 评论

@aen233 不是这个意思,这样写就是写死了。比如有不同的接口,接口1查询全部会员信息,接口2会员注册。按照现在的写法,不管什么接口都是返回“code”=0 “message”=success。

我想问的就是接口1返回 “code”=201 “message”=获取成功,接口2返回“code”=202 “message”=注册成功!

类似这样的自定义:return $this->setStatusCode(201)->success('用户登录成功...');

4年前 评论

@汪阿浠 哦,类似dingo。我选择直接写

return [
    'code'=>201,
    'message' =>'获取成功'
]

然后在中间件里判断如果存在code 和 message 就使用接口里定义的,否则使用默认的。
其实我们是整个项目组统一定义了成功都返回code=0,前端根据这个code判断成功失败的。
setStatusCode(201),这个code应该是httpStatus吧,跟代码里的code应该没有关系

4年前 评论

请问是在控制器里指定中间件吗?

4年前 评论

@LLLLL1998 你可以往上翻评论的回复哦,第6楼里写了,全局中间件在 app/Http/Kernel.php 中添加

4年前 评论
sea-robbers

file

file
@aen233 page方法是这样封装的嘛?

4年前 评论

@sea-robbers 看样子对着呢,你有尝试咩

4年前 评论
sea-robbers

对的,代码有点乱可以在封装一下就更完美了 :+1:

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
php @ abc
文章
20
粉丝
94
喜欢
197
收藏
231
排名:106
访问:8.9 万
私信
所有博文
社区赞助商