Skip to content

Commit

Permalink
Add support for upsert airtable api method (#69)
Browse files Browse the repository at this point in the history
* Add support for `upsert` airtable api method

* Remove redundant empty line from `\App\Airtable\AirtableApiClient`
  • Loading branch information
gabrieltakacs authored Dec 9, 2023
1 parent e6da278 commit 28681aa
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Airtable.php
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,11 @@ public function select(array $fields = [])
return $this;
}

public function upsert(array $data, array $fieldsToMergeOn)
{
return $this->api->upsert($data, $fieldsToMergeOn);
}

private function toCollection($object)
{
return isset($object['records']) ? collect($object['records']) : $object;
Expand Down
45 changes: 45 additions & 0 deletions src/Api/AirtableApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,51 @@ public function massUpdate(string $method, array $data): array
return ['records' => $records];
}

public function upsert($data = null, $fieldsToMergeOn = [])
{
$records = [];
$updatedRecords = [];
$createdRecords = [];

$chunks = array_chunk($data, 10);
foreach ($chunks as $key => $dataChunk) {
$contents = [];
foreach ($dataChunk as $dataRow) {
$contents[] = (object) [
'fields' => (object) $dataRow,
];
}

$params = ['performUpsert' => (object) ['fieldsToMergeOn' => $fieldsToMergeOn], 'records' => $contents];

$responseData = $this->decodeResponse(
$this->client->patch($this->getEndpointUrl(), $params)
);

if ($responseData->has('records')) {
$records += $responseData->get('records');
}

if ($responseData->has('updatedRecords')) {
$updatedRecords += $responseData->get('updatedRecords');
}

if ($responseData->has('createdRecords')) {
$createdRecords += $responseData->get('createdRecords');
}

if (isset($chunks[$key + 1])) {
usleep($this->delay);
}
}

return collect([
'records' => $records,
'updatedRecords' => $updatedRecords,
'createdRecords' => $createdRecords,
]);
}

public function delete(string $id)
{
$url = $this->getEndpointUrl($id);
Expand Down

0 comments on commit 28681aa

Please sign in to comment.