json返回格式设置
This commit is contained in:
112
config/response.php
Executable file
112
config/response.php
Executable file
@@ -0,0 +1,112 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use JetBrains\PhpStorm\NoReturn;
|
||||
|
||||
# 返回封装
|
||||
|
||||
/**
|
||||
* 请求成功返回
|
||||
* @param $data
|
||||
* @param $msg
|
||||
* @param $code
|
||||
* @return JsonResponse
|
||||
*/
|
||||
if ( !function_exists('jok') ) {
|
||||
function jok($data = [], $msg = '请求成功'): JsonResponse
|
||||
{
|
||||
return response()->json([
|
||||
'code' => 0,
|
||||
'message' => $msg,
|
||||
'result' => $data,
|
||||
'type' => 'success'
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求失败返回
|
||||
* @param $data
|
||||
* @param $msg
|
||||
* @param $code
|
||||
* @return JsonResponse
|
||||
*/
|
||||
if ( !function_exists('jerr') ) {
|
||||
#[NoReturn]
|
||||
function jerr($msg = '', $data = [], $code = 500): JsonResponse
|
||||
{
|
||||
exit(json_encode([
|
||||
'code' => $code,
|
||||
'message' => $msg,
|
||||
'result' => $data,
|
||||
'type' => 'error'
|
||||
], JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 异常返回(他会阻止后面所有代码的运行)
|
||||
* @param $data
|
||||
* @param $msg
|
||||
* @param $code
|
||||
* @return JsonResponse
|
||||
*/
|
||||
if ( !function_exists('jInstanceof') ) {
|
||||
function jInstanceof($code = 500, $msg = '错误返回', $data = []): JsonResponse
|
||||
{
|
||||
|
||||
// 转换成秒
|
||||
$timeDifference = microtime(true) - LARAVEL_START;
|
||||
|
||||
return response()->json([
|
||||
'code' => $code,
|
||||
'message' => $msg,
|
||||
'result' => $data,
|
||||
'type' => 'error',
|
||||
'interface_info' => [
|
||||
'result_time' => $timeDifference < 1? round($timeDifference * 1000) . ' ms': number_format($timeDifference, 1) . ' s',
|
||||
'ecs' => env('ECS')
|
||||
]
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试 (他会阻止后面所有代码的运行)
|
||||
* @param $data
|
||||
* @param $msg
|
||||
* @param $code
|
||||
* @return void
|
||||
*/
|
||||
if ( !function_exists('ds') ) {
|
||||
#[NoReturn]
|
||||
function ds($data = [], $msg = '测试返回'): void
|
||||
{
|
||||
exit(json_encode([
|
||||
'code' => 19522,
|
||||
'message' => $msg,
|
||||
'result' => $data,
|
||||
'type' => 'success'
|
||||
],JSON_UNESCAPED_SLASHES,JSON_UNESCAPED_UNICODE));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 身份过期返回(他会阻止后面所有代码的运行)
|
||||
* @param $data
|
||||
* @param $msg
|
||||
* @param $code
|
||||
* @return void
|
||||
*/
|
||||
if ( !function_exists('jexpire') ) {
|
||||
#[NoReturn]
|
||||
function jexpire($msg = '身份过期', $data = []): void
|
||||
{
|
||||
exit(json_encode([
|
||||
'code' => 401,
|
||||
'message' => $msg,
|
||||
'result' => $data,
|
||||
'type' => 'jexpire'
|
||||
],JSON_UNESCAPED_SLASHES,JSON_UNESCAPED_UNICODE));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user