vasily-kartashov/graphql-batch-processor

GraphQL batch processor

0.0.10 2021-01-10 05:00 UTC

This package is auto-updated.

Last update: 2024-04-20 09:56:51 UTC


README

Build Status

Simple Example:

// Name of the cache is `addressesByUserId`
return Batch::as('addressesByUserId')
    // Collect user IDs
    ->collectOne($user->id())
    // When all user IDs are collected, fetch addresses for all collected user IDs
    // The callback is only executed once for each set of user IDs
    // And cached internally under the name `addressesByUserId`
    ->fetchOneToMany(function (array $userIds) { 
        return $this->addressRepository->findAddressesByUserIds($userIds);
    });

More complex example

return Batch::as('accountsByOrgranizationId')
    ->collectMultiple($organization->accountIds())
    ->fetchOneToOne(function (array $accountIds) {
        return $this->accountRepository->findAccountsByAccountIds($accountIds);
    });

Proper example

Get all addresses for each user; post filter out hidden addresses; format each address as a string; if there's no address, default to company's address

return Batch::as('addressesByUserId')
    ->collectOne($user->id())
    ->filter(function (Address $address) {
        return !$address->hidden();
    })
    ->format(function (Address $address) {
        return (string) $address;
    })
    ->defaultTo([$company->defaultAddress()])
    ->fetchOneToMany(function (array $userIds) {
        return $this->addressRepository->findAddressesByUserIds($userIds);
    });

Tracing

Batches accept PSR-3 Loggers

return Batch::as('usersByUserIds')
    ->setLogger($logger)
    ->collectOne(...)
    ...