initialize method

Future<void> initialize({
  1. dynamic httpClient,
  2. SheetsApi? injectedSheetsApi,
  3. DriveApi? injectedDriveApi,
  4. required String fileName,
  5. required Map<String, List<String>> structure,
  6. List<Formula>? formulas,
  7. List<ForeignKey>? foreignKeys,
  8. Duration cacheTime = const Duration(seconds: 0),
})

Inicializa a base de dados

Implementation

Future<void> initialize({
  dynamic httpClient,
  sheets.SheetsApi? injectedSheetsApi,
  drive.DriveApi? injectedDriveApi,
  required String fileName,
  required Map<String, List<String>> structure,
  List<Formula>? formulas,
  List<ForeignKey>? foreignKeys,
  Duration cacheTime = const Duration(seconds: 0),
}) async {
  _fileName = fileName;
  _structure = structure;
  this.foreignKeys = foreignKeys;
  this.formulas = formulas;
  this.cacheTime = cacheTime;

  if (injectedDriveApi == null &&
      injectedSheetsApi == null &&
      httpClient == null) {
    throw Exception(
      "You must provide either an httpClient or injected APIs for testing.",
    );
  }

  final driveApi = injectedDriveApi ?? drive.DriveApi(httpClient!);
  final sheetsApi = injectedSheetsApi ?? sheets.SheetsApi(httpClient!);
  api = sheetsApi;

  final search = await driveApi.files.list(
    q: "name = '$_fileName' and mimeType = 'application/vnd.google-apps.spreadsheet' and trashed = false",
  );

  if (search.files != null && search.files!.isNotEmpty) {
    spreadsheetId = search.files!.first.id;
    if (foreignKeys != null) {
      await updateForeignKey(sheetsApi, foreignKeys);
    }
    if (formulas != null) {
      await _updateFormulas(sheetsApi);
    }

    // Now checks both NEW columns and name CHANGES
    await _synchronizeStructure(sheetsApi);
    await _applyAutomaticProtections(sheetsApi);
    return;
  }

  // Initial creation logic...
  var newSpreadsheet = sheets.Spreadsheet(
    properties: sheets.SpreadsheetProperties(title: _fileName),
    sheets: _structure.keys
        .map(
          (title) =>
              sheets.Sheet(properties: sheets.SheetProperties(title: title)),
        )
        .toList(),
  );

  var sheetResponse = await sheetsApi.spreadsheets.create(newSpreadsheet);
  spreadsheetId = sheetResponse.spreadsheetId;

  if (foreignKeys != null) {
    await updateForeignKey(sheetsApi, foreignKeys);
  }
  if (formulas != null) {
    await _updateFormulas(sheetsApi);
  }

  await _configureHeaders(sheetsApi);
  await _applyAutomaticProtections(sheetsApi);
}