From aeda4a59dd3fe48a23086265396ba5d9452b7e0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=9C=84=EB=8F=99=EA=B7=A0?= Date: Thu, 29 Jan 2026 15:52:20 +0900 Subject: [PATCH] =?UTF-8?q?DB=20=EC=97=B0=EA=B2=B0=20=EC=84=B8=ED=8C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/mess_api.dart | 48 ++++++++++++++++++++++++++++++++++++----------- 1 file changed, 37 insertions(+), 11 deletions(-) diff --git a/bin/mess_api.dart b/bin/mess_api.dart index 6115721..1ab3f7b 100644 --- a/bin/mess_api.dart +++ b/bin/mess_api.dart @@ -1,8 +1,9 @@ import 'dart:io'; +import 'dart:convert'; import 'package:mysql1/mysql1.dart'; import 'package:mess_api/config.dart'; -Future testDbConnection() async { +Future getTestNumber() async { final settings = ConnectionSettings( host: DBConfig.dbHost, port: DBConfig.dbPort, @@ -12,29 +13,24 @@ Future 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 + ..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.ok - ..write('ok') + ..statusCode = HttpStatus.notFound ..close(); } }