mercredi 23 mai 2018

Should data be fetched inside a Response Transformer?

Assuming there are two collections in a MongoDB Database: UsersCollection and BookingsCollection. A user can have multiple bookings, the BookingsCollection contains the user_id field to establish the reference.

In one of the endpoints, we need to deliver a response object that contains a list of users, each object in this list needs to contain the user's name and the number of bookings a user has:

[
    {
        "name": "Karim",
        "bookings": 8
    },
    {
        "name": "Julie",
        "bookings": 1
    },
    ...
]

The bookings field in the response is a virtual field that needs to be fetched by counting the number of rows on the BookingsCollection with a giver user_id.

We're using PHPLeague's Fractal Transformers in this project. I believe that this virtual field (bookings) should be in the $availableIncludes of the Transformer, but should this data be fetched inside the transformer? Or does the data need to be already in the object passed to the transformer?

Something like:

class UserTransformer extends TransformerAbstract
{
    protected $availableIncludes = [
        'membership',
        'last_interaction'
    ];

    public function transform(User $user)
    {
        return [
            'first_name' => $user->firstName(),
            'last_name' => $user->lastName(),
            'phone' => $user->phone(),
            'email' => $user->email(),
            'source' => $user->source()
        ];
    }

    public function includeBookings(User $user)
    {
        /** @var BookingsRepository $bookingRepository */
        $bookingRepository = app()->make(BookingsRepository::class);

        $bookingRepository->criteria->push( new IsBooked() );
        $bookingRepository->criteria->push( new UserId($user->id()));

        $bookings = $bookingRepository->count();

        return $bookings;
    }
}

But it doesn't feel right haha

My question is not exactly how to do it, but what would be the best place to fetch the data...

EDIT:

If the object passed to the transformer is supposed to have bookings already prefilled, wouldn't this add unnecessary complexity to all endpoints that might not be expecting to receive the bookings?

Cheers

Aucun commentaire:

Enregistrer un commentaire