diff --git a/src/Airtable.php b/src/Airtable.php index c7a3ff5..f241e20 100755 --- a/src/Airtable.php +++ b/src/Airtable.php @@ -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; diff --git a/src/Api/AirtableApiClient.php b/src/Api/AirtableApiClient.php index ca8ef13..6b7b53e 100644 --- a/src/Api/AirtableApiClient.php +++ b/src/Api/AirtableApiClient.php @@ -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);