createBulkRecords method

Future<List<AirtableRecord>> createBulkRecords(
  1. String tableName,
  2. List<Map<String, dynamic>> dataList
)

Creates multiple records in bulk in the specified tableName.

  • dataList: A list of maps, each containing field names and values for a record.

Returns a Future that resolves to a list of created AirtableRecord instances.

Throws an AirtableException if the request fails.

Implementation

Future<List<AirtableRecord>> createBulkRecords(
    String tableName, List<Map<String, dynamic>> dataList) async {
  List<AirtableRecord> createdRecords = [];
  const int batchSize = 10;

  for (int i = 0; i < dataList.length; i += batchSize) {
    final batchData = dataList.sublist(
      i,
      i + batchSize > dataList.length ? dataList.length : i + batchSize,
    );

    final requestBody = {
      'records': batchData.map((data) => {'fields': data}).toList(),
      'typecast': true,
    };

    final response = await http.post(
      Uri.parse('$_endpoint/$baseId/$tableName'),
      headers: {
        'Authorization': 'Bearer $apiKey',
        'Content-Type': 'application/json',
      },
      body: jsonEncode(requestBody),
    );

    if (response.statusCode == 200 || response.statusCode == 201) {
      final jsonData = jsonDecode(response.body);
      createdRecords.addAll((jsonData['records'] as List)
          .map((recordJson) => AirtableRecord.fromJson(recordJson))
          .toList());
    } else {
      final errorBody = jsonDecode(response.body);
      throw AirtableException(
        message: 'Failed to create records',
        details: errorBody['error']?['message'],
      );
    }
  }

  return createdRecords;
}