|
| 1 | +import 'package:flutter_news_app_api_server_full_source_code/src/database/migration.dart'; |
| 2 | +import 'package:logging/logging.dart'; |
| 3 | +import 'package:mongo_dart/mongo_dart.dart'; |
| 4 | + |
| 5 | +/// Migration to add the `logoUrl` field to existing `sources` documents. |
| 6 | +class AddLogoUrlToSources extends Migration { |
| 7 | + /// {@macro add_logo_url_to_sources} |
| 8 | + AddLogoUrlToSources() |
| 9 | + : super( |
| 10 | + prDate: '20251024000000', |
| 11 | + prId: '60', |
| 12 | + prSummary: |
| 13 | + 'Adds the required `logoUrl` field to all existing ' |
| 14 | + 'documents in the `sources` collection to align with the ' |
| 15 | + 'core v1.3.0 model update.', |
| 16 | + ); |
| 17 | + |
| 18 | + @override |
| 19 | + Future<void> up(Db db, Logger log) async { |
| 20 | + final collection = db.collection('sources'); |
| 21 | + final sourcesToUpdate = await collection |
| 22 | + .find(where.notExists('logoUrl')) |
| 23 | + .toList(); |
| 24 | + |
| 25 | + if (sourcesToUpdate.isEmpty) { |
| 26 | + log.info('No sources found needing a logoUrl. Migration is up to date.'); |
| 27 | + return; |
| 28 | + } |
| 29 | + |
| 30 | + log.info( |
| 31 | + 'Found ${sourcesToUpdate.length} sources to update with a logoUrl.', |
| 32 | + ); |
| 33 | + var count = 0; |
| 34 | + for (final source in sourcesToUpdate) { |
| 35 | + final sourceUrl = source['url'] as String?; |
| 36 | + if (sourceUrl != null && sourceUrl.isNotEmpty) { |
| 37 | + try { |
| 38 | + final host = Uri.parse(sourceUrl).host; |
| 39 | + final logoUrl = 'https://logo.clearbit.com/$host?size=200'; |
| 40 | + await collection.updateOne( |
| 41 | + where.id(source['_id'] as ObjectId), |
| 42 | + modify.set('logoUrl', logoUrl), |
| 43 | + ); |
| 44 | + count++; |
| 45 | + } catch (e) { |
| 46 | + log.warning( |
| 47 | + 'Could not parse URL for source ${source['_id']}: $sourceUrl', |
| 48 | + ); |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + log.info('Updated $count sources with a new logoUrl.'); |
| 53 | + } |
| 54 | + |
| 55 | + @override |
| 56 | + Future<void> down(Db db, Logger log) async { |
| 57 | + final collection = db.collection('sources'); |
| 58 | + await collection.updateMany( |
| 59 | + where.exists('logoUrl'), |
| 60 | + modify.unset('logoUrl'), |
| 61 | + ); |
| 62 | + log.info( |
| 63 | + 'Removed "logoUrl" field from all documents in the sources collection.', |
| 64 | + ); |
| 65 | + } |
| 66 | +} |
0 commit comments