upsert method

Future<T?> upsert({
  1. Map<String, dynamic>? where,
  2. List<String>? uniqueBy,
  3. Map<String, dynamic>? data,
  4. Map<String, dynamic>? createData,
  5. Map<String, dynamic>? updateData,
  6. List<String>? excludeUpdatedData,
})

Universal upsert for Flint Dart.

Implementation

Future<T?> upsert({
  Map<String, dynamic>? where,
  List<String>? uniqueBy,
  Map<String, dynamic>? data,
  Map<String, dynamic>? createData,
  Map<String, dynamic>? updateData,
  List<String>? excludeUpdatedData,
}) async {
  if (where == null) {
    if (uniqueBy == null || uniqueBy.isEmpty) {
      throw Exception('upsert requires either where or uniqueBy');
    }
  }

  final hasOldApi = data != null;
  final hasNewApi = createData != null || updateData != null;

  if (!hasOldApi && !hasNewApi) {
    throw Exception(
      'upsert requires either `data` or (`createData` / `updateData`)',
    );
  }

  if (hasOldApi && hasNewApi) {
    throw Exception(
      'Use either `data` or (`createData` / `updateData`), not both',
    );
  }

  if (!hasOldApi &&
      excludeUpdatedData != null &&
      excludeUpdatedData.isNotEmpty) {
    throw Exception(
      '`excludeUpdatedData` can only be used with the legacy `data` payload',
    );
  }

  late final Map<String, dynamic> resolvedCreateData;
  late final Map<String, dynamic> resolvedUpdateData;

  if (hasOldApi) {
    final sharedData = Map<String, dynamic>.from(data);
    resolvedCreateData = Map<String, dynamic>.from(sharedData);
    resolvedUpdateData = Map<String, dynamic>.from(sharedData);

    if (excludeUpdatedData != null && excludeUpdatedData.isNotEmpty) {
      for (final key in excludeUpdatedData) {
        resolvedUpdateData.remove(key);
      }
    }
  } else {
    resolvedCreateData = Map<String, dynamic>.from(createData ?? {});
    resolvedUpdateData = Map<String, dynamic>.from(updateData ?? {});
  }

  if (where == null) {
    final resolvedUniqueBy = uniqueBy!;
    final source = {
      ...resolvedCreateData,
      ...resolvedUpdateData,
    };

    where = {};

    for (final key in resolvedUniqueBy) {
      if (!source.containsKey(key)) {
        throw Exception(
          'Missing unique key "$key" in payload for upsert',
        );
      }
      where[key] = source[key];
    }
  } else {
    where = Map<String, dynamic>.from(where);
  }

  var queryModel = resetQuery();
  where.forEach((key, value) {
    queryModel.qb.where(key, '=', value);
  });

  final existing = await queryModel.first();

  if (existing != null) {
    if (resolvedUpdateData.isEmpty) {
      return existing;
    }
    return await existing.update(data: resolvedUpdateData);
  }

  if (resolvedCreateData.isEmpty) {
    throw Exception('No create data available for insert');
  }

  final insertData = {
    ...where,
    ...resolvedCreateData,
  };

  return await create(insertData);
}