saloon icon indicating copy to clipboard operation
saloon copied to clipboard

Feature | Add BatchRequest for handling batched API requests

Open mstfblci opened this issue 1 year ago • 3 comments

Description

I am working with hotel providers, where one provider can return prices for multiple rooms in a single request, while another provider requires separate requests for each room. This approach became necessary to handle such cases efficiently.

Additionally, for some of the providers I work with, there are situations where I need to send requests to multiple endpoints and process the results accordingly, making this solution quite useful.

Below is an example of how I handle batch requests in such cases

Example

<?php

namespace Hotel\Providers\ExampleProvider\Services;

use Illuminate\Support\Collection;
use Saloon\Http\BatchRequest;
use Saloon\Http\Request;

class AvailabilityService extends BatchRequest
{
    /**
     * @param Collection $mappings
     * @param string $startDate
     * @param string $endDate
     * @param Collection $rooms
     */
    public function __construct(protected Collection $mappings, protected string $startDate, protected string $endDate, protected Collection $rooms)
    {
        //
    }

    public function defaultRequests(): array
    {
        return $this->mappings
            ->chunk(10)
            ->flatMap(fn($mappings): Collection => $this->rooms->map(fn($room): Request => new SingleAvailabilityService($mappings, $this->startDate, $this->endDate, $room)))
            ->toArray();
    }

    public function processResponses(array $responses): mixed
    {
        // do magic
    }
}

mstfblci avatar Nov 15 '24 13:11 mstfblci

I'd appreciate your review and feedback. @Sammyjo20

mstfblci avatar Nov 15 '24 13:11 mstfblci

Hey @mstfblci apologies, I've been a bit busy with things - I will take a look for you soon :)

Sammyjo20 avatar Dec 03 '24 00:12 Sammyjo20

Hey @Sammyjo20, no worries. Just wanted to follow up—whenever you get a chance, could you also take a look at my latest PR? Thanks!”

mstfblci avatar Mar 19 '25 13:03 mstfblci