所以我使用分形transformer来美化我的用户模型json返回(使用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
我认为自定义响应的显而易见的地方是分形默认dataArraySerializer。但我不确定如何处理错误参数..即如果它存在而不是仅将其硬编码为null,如何将其传递给实际错误
答案 0 :(得分:0)
所以这就是我修复它的原因(但由于某种原因,我对这整个情况并不满意,是一个熟悉rails / django之类的laravel nuub ......有些事情并不合适所有这一切:)
<?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
}