-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhelpers.php
56 lines (43 loc) · 1.49 KB
/
helpers.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
function prepare_data_payload($chunk, $fieldsToMergeOn) {
$dataPayload = [
'typecast' => true,
'performUpsert' => [
'fieldsToMergeOn' => [$fieldsToMergeOn]
],
'records' => array_map(function($record) {
return ['fields' => $record];
}, $chunk)
];
return $dataPayload;
}
function send_request($client, $url, $dataPayload) {
$response = $client->patch($url, [
'json' => $dataPayload
]);
$responseData = json_decode($response->getBody(), true);
return $responseData;
}
function upsert_to_airtable($baseId, $tableId, $apiKey, $records, $fieldsToMergeOn) {
$chunks = array_chunk($records, 10); // Chunk records into batches of 10
$client = new Client([
'base_uri' => 'https://api.airtable.com/v0/',
'headers' => [
'Authorization' => 'Bearer ' . $apiKey,
'Content-Type' => 'application/json'
]
]);
$url = "{$baseId}/{$tableId}";
foreach ($chunks as $chunk) {
$dataPayload = prepare_data_payload($chunk, $fieldsToMergeOn);
$responseData = send_request($client, $url, $dataPayload);
if (isset($responseData['records'])) {
echo "Successfully upserted " . count($responseData['records']) . " records to Airtable\n";
} else {
echo "Upsert to Airtable failed. Error message: {$responseData['error']['message']}\n";
}
}
}
?>