我正在使用Fractal transformer来美化我的用户模型json return (使用Laravel 5.3 + dingo api)。
之前我是这样返回我的用户模型的:
return response()->success(compact('user'));返回的json如下所示
{
"errors": false,
"data": {
"user": {
"id": 2,
"first_name": "现在我使用一个转换器,并像这样返回它:
return $this->response->item($user, new UserTransformer);json看起来像这样:
{
"data": {
"id": 2,
"first_name": "Client",
"last_name": "Testing",我如何使用分形将事物连接起来,以返回与之前相同的结构?我的所有单元测试都期望原始格式,所以它们失败了,如下所示:
1) LoginEmailTest::testLoginEmailSuccess
Unable to find JSON fragment
["errors":false]
within
[{"data":[{"user":{"a更新
我认为自定义响应的最明显的地方是在Fractal默认dataArraySerializer中。但是我不确定如何处理error参数,换句话说,如果它存在,我如何传递给它一个实际的错误,而不是仅仅将它硬编码为null?
发布于 2018-02-08 15:06:41
这就是我修复它的方法(但出于某种原因,我对整个情况并不满意,因为我是一个幼年的nuub,但对rails/django等很熟悉。这一切让人感觉有些不对劲:)
<?php
/*
* This is to address the problem asked here:
* https://stackoverflow.com/questions/48669423/how-to-make-the-error-false-appear-in-fractal-json-response
* basically we must add an error key to the top level of the json response
*
*
*/
namespace App\Http\Serializer;
use League\Fractal\Serializer\ArraySerializer;
class DataErrorArraySerializer extends ArraySerializer
{
/**
* Serialize a collection.
*
* @param string $resourceKey
* @param array $data
*
* @return array
*/
public function collection($resourceKey, array $data)
{
return ['data' => $data, 'errors' => false];
}
/**
* Serialize an item.
*
* @param string $resourceKey
* @param array $data
*
* @return array
*/
public function item($resourceKey, array $data)
{
return ['data' => $data, 'errors' => false];
}
/**
* Serialize null resource.
*
* @return array
*/
public function null()
{
return ['data' => [], 'errors' => false];
}
}在控制器中:
$manager = new Manager();
$manager->setSerializer(new DataErrorArraySerializer());
$resource = new Item($user, new UserTransformer);
return $manager->createData($resource)->toArray();下面是一个成功的http请求的样子:
{
"data": {
"id": 2,
"first_name": "Client",
"last_name": "Testing",
..
},
"errors": false
}当http错误发生时,它甚至不会执行该代码,它将返回一个错误响应(例如,请参阅以下代码部分:
} catch (\JWTException $e) {
\Log::debug('Could not create token for login email: '. $email);
return response()->error(trans('errors.no_token'), 500);
}响应在public/index.php中定义如下:
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
$response->send();无论如何,这是错误的样子:
{
"message": "422 Unprocessable Entity",
"errors": {
"message": [
"The email must be a valid email address."
]
},
"status_code": 422
}https://stackoverflow.com/questions/48669423
复制相似问题