feat: Add hierarchy endpoint

This commit is contained in:
Mangiang 2021-10-12 22:31:29 -04:00
parent 40953db00f
commit a8a485a2c2
3 changed files with 55 additions and 3 deletions

View File

@ -134,4 +134,33 @@ class ItemsCollection
'locale' => $this->locales[$locale][$id] ?? '' 'locale' => $this->locales[$locale][$id] ?? ''
]; ];
} }
public function getHierarchy(string $id, string $locale = 'en'): Collection {
// Return 404 if the item does not exist
$itemData = $this->items[$id] ?? throw new ItemNotFoundException('Item not found');
// Initialize the hierarchy with the current item
$item = [
'_id' => $itemData['_id'],
'_name' => $itemData['_name'],
'_parent' => $itemData['_parent'],
'locale' => $this->locales[$locale][$id] ?? ''
];
$hierarchy = collect([$id => $item]);
// Check the whole hierarchy and merge into the return variable
while (!empty($item['_parent'] ?? '')) {
$itemtId = $item['_parent'];
$itemData = $this->items[$itemtId] ?? null;
$item = [
'_id' => $itemData['_id'],
'_name' => $itemData['_name'],
'_parent' => $itemData['_parent'],
'locale' => $this->locales[$locale][$itemtId] ?? ''
];
$hierarchy = $hierarchy->merge([$itemtId => $item]);
}
return $hierarchy;
}
} }

View File

@ -60,6 +60,26 @@ class ItemController extends Controller
} }
} }
/**
* @param Request $request The request
* @return JsonResponse Either {"error":"item not found"} or an object containing
* for each id, an object looking like
* {"item":{"_id":"id","_name":"name","_parent":"parent"}, "locale": {"Description":"description", "Name":"name", "ShortName":"shortName"}}
*/
public function getHierarchy(Request $request): JsonResponse
{
try {
return response()->json($this->itemsCollection->getHierarchy($request->id, $request->locale ?? 'en'));
} catch (Throwable $exception) {
Log::error($exception->getMessage());
Log::error($exception->getTraceAsString());
return response()->json([
'error' => 'Item not found.',
], Response::HTTP_NOT_FOUND);
}
}
/** /**
* @return JsonResponse * @return JsonResponse
*/ */

View File

@ -18,7 +18,10 @@ $router->get('/', function () {
}); });
$router->get('/api/locales', 'ItemController@getLocales'); $router->get('/api/locales', 'ItemController@getLocales');
$router->get('/api/refresh', 'ItemController@refreshAllCache');
$router->post('/api/search', 'ItemController@search');
$router->get('/api/item', 'ItemController@getItem');
$router->get('/api/refresh', 'ItemController@refreshAllCache');
$router->post('/api/search', 'ItemController@search');
$router->get('/api/item/hierarchy', 'ItemController@getHierarchy');
$router->get('/api/item', 'ItemController@getItem');