Skip to content

Commit

Permalink
refactor: Improve Redis middleware implementation and add no-op comma…
Browse files Browse the repository at this point in the history
…nd fallback
  • Loading branch information
0niel committed Feb 5, 2025
1 parent bda3178 commit dcdd94d
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 10 deletions.
3 changes: 2 additions & 1 deletion api/lib/src/middleware/redis_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ Middleware redisProvider() {
return (handler) {
return (context) async {
final redis = await RedisClient.instance;
return handler.use(provider<RedisClient>((_) => redis))(context);
final updatedContext = context.provide<RedisClient>(() => redis);
return handler(updatedContext);
};
};
}
25 changes: 22 additions & 3 deletions api/lib/src/redis.dart
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,13 @@ class RedisClient {
if (_connection == null || _command == null) {
try {
final conn = RedisConnection();
print('Connecting to Redis..., ${_appConfig.redisHost}, ${_appConfig.redisPort}');
print('Connecting to Redis... ${_appConfig.redisHost}, ${_appConfig.redisPort}');
_command = await conn.connect(_appConfig.redisHost, _appConfig.redisPort);
_connection = conn;
} catch (e, s) {
Error.throwWithStackTrace('Failed to connect to Redis.', s);
} catch (e) {
print('Failed to connect to Redis: $e\nFalling back to no-op Redis.');
// Fallback to a no-op command so that errors related to Redis are suppressed.
_command = NullCommand();
}
}
}
Expand All @@ -50,3 +52,20 @@ class RedisClient {
return _command!;
}
}

/// A no-operation [Command] that safely ignores calls.
class NullCommand implements Command {
@override
// ignore: non_constant_identifier_names
Future<dynamic> send_object(Object args) async {
return null;
}

@override
Future<dynamic> get(String key) async {
return null;
}

@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
12 changes: 6 additions & 6 deletions api/routes/_middleware.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import 'package:university_app_server_api/api.dart';

Handler middleware(Handler handler) {
return handler
.use(loggerProvider())
.use(redisProvider())
.use(requestLogger())
.use(userProvider())
.use(newsDataSourceProvider())
.use(communityDataSourceProvider())
.use(scheduleDataSourceProvider())
.use(communityDataSourceProvider());
.use(newsDataSourceProvider())
.use(userProvider())
.use(requestLogger())
.use(loggerProvider())
.use(redisProvider());
}

0 comments on commit dcdd94d

Please sign in to comment.