Skip to content

Enhance data route #41

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Aug 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 16 additions & 68 deletions lib/src/middlewares/data_fetch_middleware.dart
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import 'package:core/core.dart';
import 'package:dart_frog/dart_frog.dart';
import 'package:data_repository/data_repository.dart';
import 'package:flutter_news_app_api_server_full_source_code/src/middlewares/ownership_check_middleware.dart';
import 'package:flutter_news_app_api_server_full_source_code/src/services/dashboard_summary_service.dart';
import 'package:flutter_news_app_api_server_full_source_code/src/registry/data_operation_registry.dart';
import 'package:logging/logging.dart';

final _log = Logger('DataFetchMiddleware');
Expand Down Expand Up @@ -31,9 +30,7 @@ Middleware dataFetchMiddleware() {
final item = await _fetchItem(context, modelName, id);

if (item == null) {
_log.warning(
'Item not found for model "$modelName", id "$id".',
);
_log.warning('Item not found for model "$modelName", id "$id".');
throw NotFoundException(
'The requested item of type "$modelName" with id "$id" was not found.',
);
Expand All @@ -50,79 +47,30 @@ Middleware dataFetchMiddleware() {
}

/// Helper function to fetch an item from the correct repository based on the
/// model name.
/// model name by using the [DataOperationRegistry].
///
/// This function contains the switch statement that maps a `modelName` string
/// to a specific `DataRepository` call.
/// This function looks up the appropriate fetcher function from the registry
/// and invokes it. This avoids a large `switch` statement and makes the
/// system easily extensible.
///
/// Throws [OperationFailedException] for unsupported model types.
Future<dynamic> _fetchItem(
RequestContext context,
String modelName,
String id,
) async {
// The `userId` is not needed here because this middleware's purpose is to
// fetch the item regardless of ownership. Ownership is checked in a
// subsequent middleware. We pass `null` for `userId` to ensure we are
// performing a global lookup for the item.
const String? userId = null;

try {
switch (modelName) {
case 'headline':
return await context.read<DataRepository<Headline>>().read(
id: id,
userId: userId,
);
case 'topic':
return await context
.read<DataRepository<Topic>>()
.read(id: id, userId: userId);
case 'source':
return await context.read<DataRepository<Source>>().read(
id: id,
userId: userId,
);
case 'country':
return await context.read<DataRepository<Country>>().read(
id: id,
userId: userId,
);
case 'language':
return await context.read<DataRepository<Language>>().read(
id: id,
userId: userId,
);
case 'user':
return await context
.read<DataRepository<User>>()
.read(id: id, userId: userId);
case 'user_app_settings':
return await context.read<DataRepository<UserAppSettings>>().read(
id: id,
userId: userId,
);
case 'user_content_preferences':
return await context
.read<DataRepository<UserContentPreferences>>()
.read(
id: id,
userId: userId,
);
case 'remote_config':
return await context.read<DataRepository<RemoteConfig>>().read(
id: id,
userId: userId,
);
case 'dashboard_summary':
// This is a special case that doesn't use a standard repository.
return await context.read<DashboardSummaryService>().getSummary();
default:
_log.warning('Unsupported model type "$modelName" for fetch operation.');
throw OperationFailedException(
'Unsupported model type "$modelName" for fetch operation.',
);
final registry = context.read<DataOperationRegistry>();
final fetcher = registry.itemFetchers[modelName];

if (fetcher == null) {
_log.warning('Unsupported model type "$modelName" for fetch operation.');
throw OperationFailedException(
'Unsupported model type "$modelName" for fetch operation.',
);
}

return await fetcher(context, id);
} on NotFoundException {
// The repository will throw this if the item doesn't exist.
// We return null to let the main middleware handler throw a more
Expand Down
240 changes: 240 additions & 0 deletions lib/src/registry/data_operation_registry.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,240 @@
import 'package:core/core.dart';
import 'package:dart_frog/dart_frog.dart';
import 'package:data_repository/data_repository.dart';
import 'package:flutter_news_app_api_server_full_source_code/src/middlewares/ownership_check_middleware.dart';
import 'package:flutter_news_app_api_server_full_source_code/src/services/dashboard_summary_service.dart';

// --- Typedefs for Data Operations ---

/// A function that fetches a single item by its ID.
typedef ItemFetcher =
Future<dynamic> Function(RequestContext context, String id);

/// A function that fetches a paginated list of items.
typedef AllItemsReader =
Future<PaginatedResponse<dynamic>> Function(
RequestContext context,
String? userId,
Map<String, dynamic>? filter,
List<SortOption>? sort,
PaginationOptions? pagination,
);

/// A function that creates a new item.
typedef ItemCreator =
Future<dynamic> Function(
RequestContext context,
dynamic item,
String? userId,
);

/// A function that updates an existing item.
typedef ItemUpdater =
Future<dynamic> Function(
RequestContext context,
String id,
dynamic item,
String? userId,
);

/// A function that deletes an item by its ID.
typedef ItemDeleter =
Future<void> Function(RequestContext context, String id, String? userId);

/// {@template data_operation_registry}
/// A centralized registry for all data handling functions (CRUD operations).
///
/// This class uses a map-based strategy to associate model names (strings)
/// with their corresponding data operation functions. This approach avoids
/// large, repetitive `switch` statements in the route handlers, making the
/// code more maintainable, scalable, and easier to read.
///
/// By centralizing these mappings, we create a single source of truth for how
/// data operations are performed for each model, improving consistency across
/// the API.
/// {@endtemplate}
class DataOperationRegistry {
/// {@macro data_operation_registry}
DataOperationRegistry() {
_registerOperations();
}

// --- Private Maps to Hold Operation Functions ---

final Map<String, ItemFetcher> _itemFetchers = {};
final Map<String, AllItemsReader> _allItemsReaders = {};
final Map<String, ItemCreator> _itemCreators = {};
final Map<String, ItemUpdater> _itemUpdaters = {};
final Map<String, ItemDeleter> _itemDeleters = {};

// --- Public Getters to Access Operation Maps ---

/// Provides access to the map of item fetcher functions.
Map<String, ItemFetcher> get itemFetchers => _itemFetchers;

/// Provides access to the map of collection reader functions.
Map<String, AllItemsReader> get allItemsReaders => _allItemsReaders;

/// Provides access to the map of item creator functions.
Map<String, ItemCreator> get itemCreators => _itemCreators;

/// Provides access to the map of item updater functions.
Map<String, ItemUpdater> get itemUpdaters => _itemUpdaters;

/// Provides access to the map of item deleter functions.
Map<String, ItemDeleter> get itemDeleters => _itemDeleters;

/// Populates the operation maps with their respective functions.
void _registerOperations() {
// --- Register Item Fetchers ---
_itemFetchers.addAll({
'headline': (c, id) =>
c.read<DataRepository<Headline>>().read(id: id, userId: null),
'topic': (c, id) =>
c.read<DataRepository<Topic>>().read(id: id, userId: null),
'source': (c, id) =>
c.read<DataRepository<Source>>().read(id: id, userId: null),
'country': (c, id) =>
c.read<DataRepository<Country>>().read(id: id, userId: null),
'language': (c, id) =>
c.read<DataRepository<Language>>().read(id: id, userId: null),
'user': (c, id) =>
c.read<DataRepository<User>>().read(id: id, userId: null),
'user_app_settings': (c, id) =>
c.read<DataRepository<UserAppSettings>>().read(id: id, userId: null),
'user_content_preferences': (c, id) => c
.read<DataRepository<UserContentPreferences>>()
.read(id: id, userId: null),
'remote_config': (c, id) =>
c.read<DataRepository<RemoteConfig>>().read(id: id, userId: null),
'dashboard_summary': (c, id) =>
c.read<DashboardSummaryService>().getSummary(),
});

// --- Register "Read All" Readers ---
_allItemsReaders.addAll({
'headline': (c, uid, f, s, p) => c
.read<DataRepository<Headline>>()
.readAll(userId: uid, filter: f, sort: s, pagination: p),
'topic': (c, uid, f, s, p) => c.read<DataRepository<Topic>>().readAll(
userId: uid,
filter: f,
sort: s,
pagination: p,
),
'source': (c, uid, f, s, p) => c.read<DataRepository<Source>>().readAll(
userId: uid,
filter: f,
sort: s,
pagination: p,
),
'country': (c, uid, f, s, p) => c.read<DataRepository<Country>>().readAll(
userId: uid,
filter: f,
sort: s,
pagination: p,
),
'language': (c, uid, f, s, p) => c
.read<DataRepository<Language>>()
.readAll(userId: uid, filter: f, sort: s, pagination: p),
'user': (c, uid, f, s, p) => c.read<DataRepository<User>>().readAll(
userId: uid,
filter: f,
sort: s,
pagination: p,
),
});

// --- Register Item Creators ---
_itemCreators.addAll({
'headline': (c, item, uid) => c.read<DataRepository<Headline>>().create(
item: item as Headline,
userId: uid,
),
'topic': (c, item, uid) => c.read<DataRepository<Topic>>().create(
item: item as Topic,
userId: uid,
),
'source': (c, item, uid) => c.read<DataRepository<Source>>().create(
item: item as Source,
userId: uid,
),
'country': (c, item, uid) => c.read<DataRepository<Country>>().create(
item: item as Country,
userId: uid,
),
'language': (c, item, uid) => c.read<DataRepository<Language>>().create(
item: item as Language,
userId: uid,
),
'remote_config': (c, item, uid) => c
.read<DataRepository<RemoteConfig>>()
.create(item: item as RemoteConfig, userId: uid),
});

// --- Register Item Updaters ---
_itemUpdaters.addAll({
'headline': (c, id, item, uid) => c
.read<DataRepository<Headline>>()
.update(id: id, item: item as Headline, userId: uid),
'topic': (c, id, item, uid) => c.read<DataRepository<Topic>>().update(
id: id,
item: item as Topic,
userId: uid,
),
'source': (c, id, item, uid) => c.read<DataRepository<Source>>().update(
id: id,
item: item as Source,
userId: uid,
),
'country': (c, id, item, uid) => c.read<DataRepository<Country>>().update(
id: id,
item: item as Country,
userId: uid,
),
'language': (c, id, item, uid) => c
.read<DataRepository<Language>>()
.update(id: id, item: item as Language, userId: uid),
'user': (c, id, item, uid) {
final repo = c.read<DataRepository<User>>();
final existingUser = c.read<FetchedItem<dynamic>>().data as User;
final updatedUser = existingUser.copyWith(
feedActionStatus: (item as User).feedActionStatus,
);
return repo.update(id: id, item: updatedUser, userId: uid);
},
'user_app_settings': (c, id, item, uid) => c
.read<DataRepository<UserAppSettings>>()
.update(id: id, item: item as UserAppSettings, userId: uid),
'user_content_preferences': (c, id, item, uid) => c
.read<DataRepository<UserContentPreferences>>()
.update(id: id, item: item as UserContentPreferences, userId: uid),
'remote_config': (c, id, item, uid) => c
.read<DataRepository<RemoteConfig>>()
.update(id: id, item: item as RemoteConfig, userId: uid),
});

// --- Register Item Deleters ---
_itemDeleters.addAll({
'headline': (c, id, uid) =>
c.read<DataRepository<Headline>>().delete(id: id, userId: uid),
'topic': (c, id, uid) =>
c.read<DataRepository<Topic>>().delete(id: id, userId: uid),
'source': (c, id, uid) =>
c.read<DataRepository<Source>>().delete(id: id, userId: uid),
'country': (c, id, uid) =>
c.read<DataRepository<Country>>().delete(id: id, userId: uid),
'language': (c, id, uid) =>
c.read<DataRepository<Language>>().delete(id: id, userId: uid),
'user': (c, id, uid) =>
c.read<DataRepository<User>>().delete(id: id, userId: uid),
'user_app_settings': (c, id, uid) =>
c.read<DataRepository<UserAppSettings>>().delete(id: id, userId: uid),
'user_content_preferences': (c, id, uid) => c
.read<DataRepository<UserContentPreferences>>()
.delete(id: id, userId: uid),
'remote_config': (c, id, uid) =>
c.read<DataRepository<RemoteConfig>>().delete(id: id, userId: uid),
});
}
}
4 changes: 4 additions & 0 deletions routes/_middleware.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import 'package:flutter_news_app_api_server_full_source_code/src/config/app_depe
import 'package:flutter_news_app_api_server_full_source_code/src/middlewares/error_handler.dart';
import 'package:flutter_news_app_api_server_full_source_code/src/models/request_id.dart';
import 'package:flutter_news_app_api_server_full_source_code/src/rbac/permission_service.dart';
import 'package:flutter_news_app_api_server_full_source_code/src/registry/data_operation_registry.dart';
import 'package:flutter_news_app_api_server_full_source_code/src/registry/model_registry.dart';
import 'package:flutter_news_app_api_server_full_source_code/src/services/auth_service.dart';
import 'package:flutter_news_app_api_server_full_source_code/src/services/auth_token_service.dart';
Expand Down Expand Up @@ -84,6 +85,9 @@ Handler middleware(Handler handler) {
// 2. Provide all dependencies to the inner handler.
final deps = AppDependencies.instance;
return handler
.use(
provider<DataOperationRegistry>((_) => DataOperationRegistry()),
)
.use(provider<ModelRegistryMap>((_) => modelRegistry))
.use(
provider<DataRepository<Headline>>(
Expand Down
Loading
Loading