init dart api server with mysql connection
This commit is contained in:
51
bin/mess_api.dart
Normal file
51
bin/mess_api.dart
Normal file
@@ -0,0 +1,51 @@
|
||||
import 'dart:io';
|
||||
import 'package:mysql1/mysql1.dart';
|
||||
import 'package:mess_api/config.dart';
|
||||
|
||||
Future<void> testDbConnection() async {
|
||||
final settings = ConnectionSettings(
|
||||
host: DBConfig.dbHost,
|
||||
port: DBConfig.dbPort,
|
||||
user: DBConfig.dbUser,
|
||||
password: DBConfig.dbPassword,
|
||||
db: DBConfig.dbName,
|
||||
);
|
||||
|
||||
final conn = await MySqlConnection.connect(settings);
|
||||
|
||||
final results = await conn.query(
|
||||
'SELECT test_number FROM test_table LIMIT 1',
|
||||
);
|
||||
|
||||
if (results.isEmpty) {
|
||||
throw Exception('DB CONNECT FAIL: no data');
|
||||
}
|
||||
|
||||
final value = results.first['test_number'];
|
||||
|
||||
if (value != 777) {
|
||||
throw Exception('DB CONNECT FAIL: value=$value');
|
||||
}
|
||||
|
||||
print('DB CONNECT OK (777)');
|
||||
|
||||
await conn.close();
|
||||
}
|
||||
|
||||
void main() async {
|
||||
await testDbConnection();
|
||||
|
||||
final server = await HttpServer.bind(
|
||||
InternetAddress.anyIPv4,
|
||||
AppConfig.port,
|
||||
);
|
||||
|
||||
print('API server running on http://localhost:${AppConfig.port}');
|
||||
|
||||
await for (HttpRequest request in server) {
|
||||
request.response
|
||||
..statusCode = HttpStatus.ok
|
||||
..write('ok')
|
||||
..close();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user