Skip to content

Commit e43c5f3

Browse files
committed
feat(core): create server entrypoint for db connection and logging
1 parent 9b07fdb commit e43c5f3

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

lib/src/config/server.dart

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import 'dart:io';
2+
3+
import 'package:dart_frog/dart_frog.dart';
4+
import 'package:ht_api/src/config/environment_config.dart';
5+
import 'package:logging/logging.dart';
6+
import 'package:postgres/postgres.dart';
7+
8+
/// Global logger instance.
9+
final _log = Logger('ht_api');
10+
11+
/// Global PostgreSQL connection instance.
12+
late final Connection _connection;
13+
14+
/// The main entry point for the server.
15+
///
16+
/// This function is responsible for:
17+
/// 1. Setting up the global logger.
18+
/// 2. Establishing the PostgreSQL database connection.
19+
/// 3. Providing these dependencies to the Dart Frog handler.
20+
/// 4. Gracefully closing the database connection on server shutdown.
21+
Future<HttpServer> run(Handler handler, InternetAddress ip, int port) async {
22+
// 1. Setup Logger
23+
Logger.root.level = Level.ALL;
24+
Logger.root.onRecord.listen((record) {
25+
// ignore: avoid_print
26+
print(
27+
'${record.level.name}: ${record.time}: '
28+
'${record.loggerName}: ${record.message}',
29+
);
30+
});
31+
32+
// 2. Establish Database Connection
33+
_log.info('Connecting to PostgreSQL database...');
34+
_connection = await Connection.open(
35+
Endpoint.uri(Uri.parse(EnvironmentConfig.databaseUrl)),
36+
settings: const ConnectionSettings(sslMode: SslMode.prefer),
37+
);
38+
_log.info('PostgreSQL database connection established.');
39+
40+
// 3. Start the server and set up shutdown logic
41+
return serve(
42+
handler,
43+
ip,
44+
port,
45+
onShutdown: () async {
46+
_log.info('Server shutting down. Closing database connection...');
47+
await _connection.close();
48+
_log.info('Database connection closed.');
49+
},
50+
);
51+
}

0 commit comments

Comments
 (0)