Я пытаюсь имитировать функциональность c paularmstrong / normalizr в моем Laravel API.
Приведенный ниже код - только моя идея, не проверенная и, вероятно, заполненная ошибками.
Мне интересно, знает ли кто-нибудь лучший способ сделать это или кто-то написал удобный пакет, который уже делает это?
Функция контроллера
public function list(Request $request) {
$items = Item::where(['id' => $id])
->with(['sets', 'things'])
->take(2);
$data = [
'entities' => [
'items' => $this->toNormalizedResponse($items, ItemResource),
'sets' => $this->toNormalizedResponse($items, SetResource),
'things' => $this->toNormalizedResponse($items, ThingResource),
],
'result' => $items->pluck('id')
];
return response()->json($data, $this->getStatusCode(), $headers);
}
Признак нормализованных данных
<?php
use Illuminate\Http\JsonResponse;
trait NormalizeResponse
{
/**
* Normalize the data
* @param $collection
* @param string $jsonResponse Custom JsonResponse
* @param string $id
* @return array
*/
function toNormalizedResponse($collection, $jsonResponse = JsonResponse::class, $id = 'id')
{
$collection = $this->getCollection($collection);
if (is_null($collection)) {
return [];
}
$data = [];
foreach($collection as $model) {
$data[$model->$id] = new $jsonResponse($model);
}
return $data;
}
/**
* Convert to collection or return null if not an eloquent model
* @param $collection
* @return \Illuminate\Support\Collection|null
*/
private function getCollection($collection) {
if ($collection instanceof Illuminate\Database\Eloquent\Collection) {
return $collection;
}
if ($collection instanceOf \Illuminate\Database\Eloquent\Model) {
return collect([$collection]);
}
return null;
}
}
ItemResource код
<?php
namespace App\Resources;
class ItemResource extends JsonResource
{
public function toArray($request)
{
$data = [
'id' => (int) $this->id,
'name' => $this->name,
'sets' => (isset ($this->sets)) ? $this->sets->pluck('id') : [],
'things' => (isset ($this->things)) ? $this->things->pluck('id') : [],
];
return $data;
}
}
Желаемый Json Структура
{
entities: {
sets: {
23: {
id: 23,
name: 'Set 23'
},
42: {
id: 42,
name: 'Set 42'
}
},
things: {
21: {
id: 21,
name: 'Thing 21'
},
33: {
id: 33,
name: 'Thing 33'
}
},
items: {
1: {
id: 1,
name: 'Item 1',
sets: [23],
things: [33]
},
2: {
id: 2,
name: 'Item 2',
sets: [23,42],
things: [21]
}
}
},
result: [1, 2]
}