Sep 22, 2016
0
Level 7
Design pattern for rescourceful feed?
Hi. I would love to have some feedback on a controller used by a feed page in an app that I was building. Im going into a similar project now and feel that this approach is lacking in so many ways. But im still not sure how to design a good index method...
What I need: *Filter on specific attributes *Sort on some attribute *Load x entries *Be able to pick up after the x entries and load x more... (I have considered the pagination, but not convinced since it might break consistensy if the rescource is updated while browsning??)
Okay, so heres my old code (the rescource is a "Trade"):
public function index(Request $request)
{
$validator = $this->indexValidator($request->all());
if ($validator->fails()) {
return Response::json([
'errors' => $validator->errors()->all()
], 422);
} else {
$take = intval($request->numberOfTrades) ?: 10;
$id = intval($request->id) ?: 2147483647; // ~INT limit for 32-bit builds.
$query = \App\Trade::where('id','<',$id);
// APPLY SEARCH FILTERS
$query = $this->applyFilters($query,$request);
$query->take($take)->orderBy('id','desc');
//$query->orderBy('id','desc');
$trades = $query->get();
return Response::json(
$this->transformCollection($trades)
,200);
}
}
private function applyFilters($query, $request)
{
// Search area
if ($request->has('radius')) {
$lat = $request->lat;
$lng = $request->lng;
$radius = $request->radius;
$dLat = $this->getDLat();
$dLng = $this->getDLng($lat);
// apply search radius (approximating with BBOX)
$query->where('lat','>',$lat-$radius*$dLat);
$query->where('lat','<',$lat+$radius*$dLat);
$query->where('lng','>',$lng-$radius*$dLng);
$query->where('lng','<',$lng+$radius*$dLng);
}
// Search by tags
if ($request->has('tags')) {
$tags = $request->tags;
// SEARCH BY SINGLE TAG IMPLEMENTED ONLY!
$query->where('tags','LIKE','%' . $tags . '%');
}
// Show only free/non free trades
if ($request->has('free')) {
//TODO
}
return $query;
}
Any advice is welcome. Thanks!
Please or to participate in this conversation.