DB 연결 세팅

This commit is contained in:
위동균
2026-01-29 15:52:20 +09:00
parent e197c049e4
commit aeda4a59dd

View File

@@ -1,8 +1,9 @@
import 'dart:io';
import 'dart:convert';
import 'package:mysql1/mysql1.dart';
import 'package:mess_api/config.dart';
Future<void> testDbConnection() async {
Future<int> getTestNumber() async {
final settings = ConnectionSettings(
host: DBConfig.dbHost,
port: DBConfig.dbPort,
@@ -12,29 +13,24 @@ Future<void> testDbConnection() async {
);
final conn = await MySqlConnection.connect(settings);
final results = await conn.query(
'SELECT test_number FROM test_table LIMIT 1',
);
await conn.close();
if (results.isEmpty) {
throw Exception('DB CONNECT FAIL: no data');
}
final value = results.first['test_number'];
final value = results.first['test_number'] as int;
if (value != 777) {
throw Exception('DB CONNECT FAIL: value=$value');
}
print('DB CONNECT OK (777)');
await conn.close();
return value;
}
void main() async {
await testDbConnection();
final server = await HttpServer.bind(
InternetAddress.anyIPv4,
AppConfig.port,
@@ -43,9 +39,39 @@ void main() async {
print('API server running on http://localhost:${AppConfig.port}');
await for (HttpRequest request in server) {
// CORS
request.response.headers
..set('Access-Control-Allow-Origin', '*')
..set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
..set('Access-Control-Allow-Headers', 'Content-Type');
if (request.method == 'OPTIONS') {
request.response
..statusCode = HttpStatus.ok
..write('ok')
..close();
continue;
}
if (request.uri.path == '/db') {
try {
final value = await getTestNumber();
request.response
..statusCode = HttpStatus.ok
..headers.contentType = ContentType.json
..write(jsonEncode({'value': value}))
..close();
} catch (e) {
request.response
..statusCode = HttpStatus.internalServerError
..headers.contentType = ContentType.json
..write(jsonEncode({'error': e.toString()}))
..close();
}
continue;
}
request.response
..statusCode = HttpStatus.notFound
..close();
}
}