Skip to content

Conversation

@mstfblci
Copy link
Contributor

@mstfblci mstfblci commented Nov 15, 2024

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
Copy link
Contributor Author

I'd appreciate your review and feedback. @Sammyjo20

@Sammyjo20
Copy link
Member

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

@Sammyjo20 Sammyjo20 changed the title Add BatchRequest for handling batched API requests Feature | Add BatchRequest for handling batched API requests Dec 3, 2024
@mstfblci
Copy link
Contributor Author

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!”

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants