fix: API 응답 파싱 오류 수정 및 에러 처리 개선
주요 변경사항: - 창고 관리 API 응답 구조와 DTO 불일치 수정 - WarehouseLocationDto에 code, manager_phone 필드 추가 - RemoteDataSource에서 API 응답을 DTO 구조에 맞게 변환 - 회사 관리 API 응답 파싱 오류 수정 - CompanyResponse의 필수 필드를 nullable로 변경 - PaginatedResponse 구조 매핑 로직 개선 - 에러 처리 및 로깅 개선 - Service Layer에 상세 에러 로깅 추가 - Controller에서 에러 타입별 처리 - 새로운 유틸리티 추가 - ResponseInterceptor: API 응답 정규화 - DebugLogger: 디버깅 도구 - HealthCheckService: 서버 상태 확인 - 문서화 - API 통합 테스트 가이드 - 에러 분석 보고서 - 리팩토링 계획서
This commit is contained in:
@@ -4,6 +4,7 @@ import '../../../core/config/environment.dart';
|
||||
import 'interceptors/auth_interceptor.dart';
|
||||
import 'interceptors/error_interceptor.dart';
|
||||
import 'interceptors/logging_interceptor.dart';
|
||||
import 'interceptors/response_interceptor.dart';
|
||||
|
||||
/// API 클라이언트 클래스
|
||||
class ApiClient {
|
||||
@@ -18,15 +19,20 @@ class ApiClient {
|
||||
|
||||
ApiClient._internal() {
|
||||
try {
|
||||
print('[ApiClient] 초기화 시작');
|
||||
_dio = Dio(_baseOptions);
|
||||
print('[ApiClient] Dio 인스턴스 생성 완료');
|
||||
print('[ApiClient] Base URL: ${_dio.options.baseUrl}');
|
||||
print('[ApiClient] Connect Timeout: ${_dio.options.connectTimeout}');
|
||||
print('[ApiClient] Receive Timeout: ${_dio.options.receiveTimeout}');
|
||||
_setupInterceptors();
|
||||
} catch (e) {
|
||||
print('Error while creating ApiClient');
|
||||
print('Stack trace:');
|
||||
print(StackTrace.current);
|
||||
print('[ApiClient] 인터셉터 설정 완료');
|
||||
} catch (e, stackTrace) {
|
||||
print('[ApiClient] ⚠️ 에러 발생: $e');
|
||||
print('[ApiClient] Stack trace: $stackTrace');
|
||||
// 기본값으로 초기화
|
||||
_dio = Dio(BaseOptions(
|
||||
baseUrl: 'http://localhost:8080/api/v1',
|
||||
baseUrl: 'https://superport.naturebridgeai.com/api/v1',
|
||||
connectTimeout: const Duration(seconds: 30),
|
||||
receiveTimeout: const Duration(seconds: 30),
|
||||
headers: {
|
||||
@@ -35,6 +41,7 @@ class ApiClient {
|
||||
},
|
||||
));
|
||||
_setupInterceptors();
|
||||
print('[ApiClient] 기본값으로 초기화 완료');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,7 +66,7 @@ class ApiClient {
|
||||
} catch (e) {
|
||||
// Environment가 초기화되지 않은 경우 기본값 사용
|
||||
return BaseOptions(
|
||||
baseUrl: 'http://localhost:8080/api/v1',
|
||||
baseUrl: 'https://superport.naturebridgeai.com/api/v1',
|
||||
connectTimeout: const Duration(seconds: 30),
|
||||
receiveTimeout: const Duration(seconds: 30),
|
||||
headers: {
|
||||
@@ -77,13 +84,7 @@ class ApiClient {
|
||||
void _setupInterceptors() {
|
||||
_dio.interceptors.clear();
|
||||
|
||||
// 인증 인터셉터
|
||||
_dio.interceptors.add(AuthInterceptor());
|
||||
|
||||
// 에러 처리 인터셉터
|
||||
_dio.interceptors.add(ErrorInterceptor());
|
||||
|
||||
// 로깅 인터셉터 (개발 환경에서만)
|
||||
// 로깅 인터셉터 (개발 환경에서만) - 가장 먼저 추가하여 모든 요청/응답을 로깅
|
||||
try {
|
||||
if (Environment.enableLogging && kDebugMode) {
|
||||
_dio.interceptors.add(LoggingInterceptor());
|
||||
@@ -94,6 +95,15 @@ class ApiClient {
|
||||
_dio.interceptors.add(LoggingInterceptor());
|
||||
}
|
||||
}
|
||||
|
||||
// 인증 인터셉터 - 요청에 토큰 추가 및 401 처리
|
||||
_dio.interceptors.add(AuthInterceptor(_dio));
|
||||
|
||||
// 응답 정규화 인터셉터 - 성공 응답을 일관된 형식으로 변환
|
||||
_dio.interceptors.add(ResponseInterceptor());
|
||||
|
||||
// 에러 처리 인터셉터 - 마지막에 추가하여 모든 에러를 캐치
|
||||
_dio.interceptors.add(ErrorInterceptor());
|
||||
}
|
||||
|
||||
/// 토큰 업데이트
|
||||
@@ -133,6 +143,9 @@ class ApiClient {
|
||||
ProgressCallback? onSendProgress,
|
||||
ProgressCallback? onReceiveProgress,
|
||||
}) {
|
||||
print('[ApiClient] POST 요청 시작: $path');
|
||||
print('[ApiClient] 요청 데이터: $data');
|
||||
|
||||
return _dio.post<T>(
|
||||
path,
|
||||
data: data,
|
||||
@@ -141,7 +154,18 @@ class ApiClient {
|
||||
cancelToken: cancelToken,
|
||||
onSendProgress: onSendProgress,
|
||||
onReceiveProgress: onReceiveProgress,
|
||||
);
|
||||
).then((response) {
|
||||
print('[ApiClient] POST 응답 수신: ${response.statusCode}');
|
||||
return response;
|
||||
}).catchError((error) {
|
||||
print('[ApiClient] POST 에러 발생: $error');
|
||||
if (error is DioException) {
|
||||
print('[ApiClient] DioException 타입: ${error.type}');
|
||||
print('[ApiClient] DioException 메시지: ${error.message}');
|
||||
print('[ApiClient] DioException 에러: ${error.error}');
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
|
||||
/// PUT 요청
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:dartz/dartz.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:injectable/injectable.dart';
|
||||
import 'package:superport/core/errors/exceptions.dart';
|
||||
import 'package:superport/core/errors/failures.dart';
|
||||
@@ -8,6 +9,7 @@ import 'package:superport/data/models/auth/login_response.dart';
|
||||
import 'package:superport/data/models/auth/logout_request.dart';
|
||||
import 'package:superport/data/models/auth/refresh_token_request.dart';
|
||||
import 'package:superport/data/models/auth/token_response.dart';
|
||||
import 'package:superport/core/utils/debug_logger.dart';
|
||||
|
||||
abstract class AuthRemoteDataSource {
|
||||
Future<Either<Failure, LoginResponse>> login(LoginRequest request);
|
||||
@@ -24,28 +26,149 @@ class AuthRemoteDataSourceImpl implements AuthRemoteDataSource {
|
||||
@override
|
||||
Future<Either<Failure, LoginResponse>> login(LoginRequest request) async {
|
||||
try {
|
||||
DebugLogger.logLogin('요청 시작', data: request.toJson());
|
||||
|
||||
final response = await _apiClient.post(
|
||||
'/auth/login',
|
||||
data: request.toJson(),
|
||||
);
|
||||
|
||||
DebugLogger.logApiResponse(
|
||||
url: '/auth/login',
|
||||
statusCode: response.statusCode,
|
||||
data: response.data,
|
||||
);
|
||||
|
||||
if (response.statusCode == 200 && response.data != null) {
|
||||
final loginResponse = LoginResponse.fromJson(response.data);
|
||||
return Right(loginResponse);
|
||||
final responseData = response.data;
|
||||
|
||||
// API 응답 형식 확인 및 처리
|
||||
// 형식 1: { success: bool, data: {...} }
|
||||
if (responseData is Map && responseData['success'] == true && responseData['data'] != null) {
|
||||
DebugLogger.logLogin('응답 형식 1 감지', data: {'format': 'wrapped'});
|
||||
|
||||
// 응답 데이터 구조 검증
|
||||
final dataFields = responseData['data'] as Map<String, dynamic>;
|
||||
DebugLogger.validateResponseStructure(
|
||||
dataFields,
|
||||
['accessToken', 'refreshToken', 'user'],
|
||||
responseName: 'LoginResponse.data',
|
||||
);
|
||||
|
||||
final loginResponse = DebugLogger.parseJsonWithLogging(
|
||||
responseData['data'],
|
||||
LoginResponse.fromJson,
|
||||
objectName: 'LoginResponse',
|
||||
);
|
||||
|
||||
if (loginResponse != null) {
|
||||
DebugLogger.logLogin('로그인 성공', data: {
|
||||
'userId': loginResponse.user.id,
|
||||
'userEmail': loginResponse.user.email,
|
||||
'userRole': loginResponse.user.role,
|
||||
});
|
||||
return Right(loginResponse);
|
||||
} else {
|
||||
return Left(ServerFailure(message: 'LoginResponse 파싱 실패'));
|
||||
}
|
||||
}
|
||||
// 형식 2: 직접 LoginResponse 형태
|
||||
else if (responseData is Map &&
|
||||
(responseData.containsKey('accessToken') ||
|
||||
responseData.containsKey('access_token'))) {
|
||||
DebugLogger.logLogin('응답 형식 2 감지', data: {'format': 'direct'});
|
||||
|
||||
// 응답 데이터 구조 검증
|
||||
DebugLogger.validateResponseStructure(
|
||||
responseData as Map<String, dynamic>,
|
||||
['accessToken', 'refreshToken', 'user'],
|
||||
responseName: 'LoginResponse',
|
||||
);
|
||||
|
||||
final loginResponse = DebugLogger.parseJsonWithLogging(
|
||||
responseData,
|
||||
LoginResponse.fromJson,
|
||||
objectName: 'LoginResponse',
|
||||
);
|
||||
|
||||
if (loginResponse != null) {
|
||||
DebugLogger.logLogin('로그인 성공', data: {
|
||||
'userId': loginResponse.user.id,
|
||||
'userEmail': loginResponse.user.email,
|
||||
'userRole': loginResponse.user.role,
|
||||
});
|
||||
return Right(loginResponse);
|
||||
} else {
|
||||
return Left(ServerFailure(message: 'LoginResponse 파싱 실패'));
|
||||
}
|
||||
}
|
||||
// 그 외의 경우
|
||||
else {
|
||||
DebugLogger.logError(
|
||||
'알 수 없는 응답 형식',
|
||||
additionalData: {
|
||||
'responseKeys': responseData.keys.toList(),
|
||||
'responseType': responseData.runtimeType.toString(),
|
||||
},
|
||||
);
|
||||
return Left(ServerFailure(
|
||||
message: '잘못된 응답 형식입니다.',
|
||||
));
|
||||
}
|
||||
} else {
|
||||
DebugLogger.logError(
|
||||
'비정상적인 응답',
|
||||
additionalData: {
|
||||
'statusCode': response.statusCode,
|
||||
'hasData': response.data != null,
|
||||
},
|
||||
);
|
||||
return Left(ServerFailure(
|
||||
message: response.statusMessage ?? '로그인 실패',
|
||||
));
|
||||
}
|
||||
} catch (e) {
|
||||
if (e is ApiException) {
|
||||
if (e.statusCode == 401) {
|
||||
return Left(AuthenticationFailure(
|
||||
message: '이메일 또는 비밀번호가 올바르지 않습니다.',
|
||||
));
|
||||
}
|
||||
return Left(ServerFailure(message: e.message));
|
||||
} on DioException catch (e) {
|
||||
DebugLogger.logError(
|
||||
'DioException 발생',
|
||||
error: e,
|
||||
additionalData: {
|
||||
'type': e.type.toString(),
|
||||
'message': e.message,
|
||||
'error': e.error?.toString(),
|
||||
'statusCode': e.response?.statusCode,
|
||||
},
|
||||
);
|
||||
|
||||
// ErrorInterceptor에서 변환된 예외 처리
|
||||
if (e.error is NetworkException) {
|
||||
return Left(NetworkFailure(message: (e.error as NetworkException).message));
|
||||
} else if (e.error is UnauthorizedException) {
|
||||
return Left(AuthenticationFailure(message: (e.error as UnauthorizedException).message));
|
||||
} else if (e.error is ServerException) {
|
||||
return Left(ServerFailure(message: (e.error as ServerException).message));
|
||||
}
|
||||
|
||||
// 기본 DioException 처리
|
||||
if (e.response?.statusCode == 401) {
|
||||
return Left(AuthenticationFailure(
|
||||
message: '이메일 또는 비밀번호가 올바르지 않습니다.',
|
||||
));
|
||||
}
|
||||
|
||||
// 네트워크 관련 에러 처리
|
||||
if (e.type == DioExceptionType.connectionTimeout ||
|
||||
e.type == DioExceptionType.sendTimeout ||
|
||||
e.type == DioExceptionType.receiveTimeout) {
|
||||
return Left(ServerFailure(message: '네트워크 연결 시간이 초과되었습니다. 로그인 중 오류가 발생했습니다.'));
|
||||
}
|
||||
|
||||
return Left(ServerFailure(message: e.message ?? '로그인 중 오류가 발생했습니다.'));
|
||||
} catch (e, stackTrace) {
|
||||
DebugLogger.logError(
|
||||
'예상치 못한 예외 발생',
|
||||
error: e,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
return Left(ServerFailure(message: '로그인 중 오류가 발생했습니다.'));
|
||||
}
|
||||
}
|
||||
@@ -59,7 +182,17 @@ class AuthRemoteDataSourceImpl implements AuthRemoteDataSource {
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return const Right(null);
|
||||
// API 응답이 { success: bool, data: {...} } 형태인지 확인
|
||||
if (response.data is Map && response.data['success'] == true) {
|
||||
return const Right(null);
|
||||
} else if (response.data == null) {
|
||||
// 응답 본문이 없는 경우도 성공으로 처리
|
||||
return const Right(null);
|
||||
} else {
|
||||
return Left(ServerFailure(
|
||||
message: '로그아웃 실패',
|
||||
));
|
||||
}
|
||||
} else {
|
||||
return Left(ServerFailure(
|
||||
message: response.statusMessage ?? '로그아웃 실패',
|
||||
@@ -82,8 +215,16 @@ class AuthRemoteDataSourceImpl implements AuthRemoteDataSource {
|
||||
);
|
||||
|
||||
if (response.statusCode == 200 && response.data != null) {
|
||||
final tokenResponse = TokenResponse.fromJson(response.data);
|
||||
return Right(tokenResponse);
|
||||
// API 응답이 { success: bool, data: {...} } 형태인 경우
|
||||
final responseData = response.data;
|
||||
if (responseData is Map && responseData['success'] == true && responseData['data'] != null) {
|
||||
final tokenResponse = TokenResponse.fromJson(responseData['data']);
|
||||
return Right(tokenResponse);
|
||||
} else {
|
||||
return Left(ServerFailure(
|
||||
message: '잘못된 응답 형식입니다.',
|
||||
));
|
||||
}
|
||||
} else {
|
||||
return Left(ServerFailure(
|
||||
message: response.statusMessage ?? '토큰 갱신 실패',
|
||||
|
||||
@@ -76,14 +76,31 @@ class CompanyRemoteDataSourceImpl implements CompanyRemoteDataSource {
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final apiResponse = ApiResponse<PaginatedResponse<CompanyListDto>>.fromJson(
|
||||
response.data,
|
||||
(json) => PaginatedResponse<CompanyListDto>.fromJson(
|
||||
json as Map<String, dynamic>,
|
||||
(item) => CompanyListDto.fromJson(item as Map<String, dynamic>),
|
||||
),
|
||||
);
|
||||
return apiResponse.data!;
|
||||
// API 응답을 직접 파싱
|
||||
final responseData = response.data;
|
||||
if (responseData != null && responseData['success'] == true && responseData['data'] != null) {
|
||||
final List<dynamic> dataList = responseData['data'];
|
||||
final pagination = responseData['pagination'] ?? {};
|
||||
|
||||
// CompanyListDto로 변환
|
||||
final items = dataList.map((item) => CompanyListDto.fromJson(item as Map<String, dynamic>)).toList();
|
||||
|
||||
// PaginatedResponse 생성
|
||||
return PaginatedResponse<CompanyListDto>(
|
||||
items: items,
|
||||
page: pagination['page'] ?? page,
|
||||
size: pagination['per_page'] ?? perPage,
|
||||
totalElements: pagination['total'] ?? 0,
|
||||
totalPages: pagination['total_pages'] ?? 1,
|
||||
first: (pagination['page'] ?? page) == 1,
|
||||
last: (pagination['page'] ?? page) == (pagination['total_pages'] ?? 1),
|
||||
);
|
||||
} else {
|
||||
throw ApiException(
|
||||
message: responseData?['error']?['message'] ?? 'Failed to load companies',
|
||||
statusCode: response.statusCode,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
throw ApiException(
|
||||
message: 'Failed to load companies',
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:dartz/dartz.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:injectable/injectable.dart';
|
||||
import 'package:superport/core/constants/api_endpoints.dart';
|
||||
import 'package:superport/core/errors/failures.dart';
|
||||
import 'package:superport/data/datasources/remote/api_client.dart';
|
||||
import 'package:superport/data/models/dashboard/equipment_status_distribution.dart';
|
||||
@@ -24,56 +25,59 @@ class DashboardRemoteDataSourceImpl implements DashboardRemoteDataSource {
|
||||
@override
|
||||
Future<Either<Failure, OverviewStats>> getOverviewStats() async {
|
||||
try {
|
||||
final response = await _apiClient.get('/overview/stats');
|
||||
final response = await _apiClient.get(ApiEndpoints.overviewStats);
|
||||
|
||||
if (response.data != null) {
|
||||
final stats = OverviewStats.fromJson(response.data);
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
final stats = OverviewStats.fromJson(response.data['data']);
|
||||
return Right(stats);
|
||||
} else {
|
||||
return Left(ServerFailure(message: '응답 데이터가 없습니다'));
|
||||
final errorMessage = response.data?['error']?['message'] ?? '응답 데이터가 없습니다';
|
||||
return Left(ServerFailure(message: errorMessage));
|
||||
}
|
||||
} on DioException catch (e) {
|
||||
return Left(_handleDioError(e));
|
||||
} catch (e) {
|
||||
return Left(ServerFailure(message: '통계 데이터를 가져오는 중 오류가 발생했습니다'));
|
||||
return Left(ServerFailure(message: '통계 데이터를 가져오는 중 오류가 발생했습니다: $e'));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Either<Failure, List<RecentActivity>>> getRecentActivities() async {
|
||||
try {
|
||||
final response = await _apiClient.get('/overview/recent-activities');
|
||||
final response = await _apiClient.get(ApiEndpoints.overviewRecentActivities);
|
||||
|
||||
if (response.data != null && response.data is List) {
|
||||
final activities = (response.data as List)
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
final activities = (response.data['data'] as List)
|
||||
.map((json) => RecentActivity.fromJson(json))
|
||||
.toList();
|
||||
return Right(activities);
|
||||
} else {
|
||||
return Left(ServerFailure(message: '응답 데이터가 올바르지 않습니다'));
|
||||
final errorMessage = response.data?['error']?['message'] ?? '응답 데이터가 올바르지 않습니다';
|
||||
return Left(ServerFailure(message: errorMessage));
|
||||
}
|
||||
} on DioException catch (e) {
|
||||
return Left(_handleDioError(e));
|
||||
} catch (e) {
|
||||
return Left(ServerFailure(message: '최근 활동을 가져오는 중 오류가 발생했습니다'));
|
||||
return Left(ServerFailure(message: '최근 활동을 가져오는 중 오류가 발생했습니다: $e'));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Either<Failure, EquipmentStatusDistribution>> getEquipmentStatusDistribution() async {
|
||||
try {
|
||||
final response = await _apiClient.get('/equipment/status-distribution');
|
||||
final response = await _apiClient.get(ApiEndpoints.overviewEquipmentStatus);
|
||||
|
||||
if (response.data != null) {
|
||||
final distribution = EquipmentStatusDistribution.fromJson(response.data);
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
final distribution = EquipmentStatusDistribution.fromJson(response.data['data']);
|
||||
return Right(distribution);
|
||||
} else {
|
||||
return Left(ServerFailure(message: '응답 데이터가 없습니다'));
|
||||
final errorMessage = response.data?['error']?['message'] ?? '응답 데이터가 없습니다';
|
||||
return Left(ServerFailure(message: errorMessage));
|
||||
}
|
||||
} on DioException catch (e) {
|
||||
return Left(_handleDioError(e));
|
||||
} catch (e) {
|
||||
return Left(ServerFailure(message: '장비 상태 분포를 가져오는 중 오류가 발생했습니다'));
|
||||
return Left(ServerFailure(message: '장비 상태 분포를 가져오는 중 오류가 발생했습니다: $e'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,22 +85,23 @@ class DashboardRemoteDataSourceImpl implements DashboardRemoteDataSource {
|
||||
Future<Either<Failure, List<ExpiringLicense>>> getExpiringLicenses({int days = 30}) async {
|
||||
try {
|
||||
final response = await _apiClient.get(
|
||||
'/licenses/expiring-soon',
|
||||
ApiEndpoints.licensesExpiring,
|
||||
queryParameters: {'days': days},
|
||||
);
|
||||
|
||||
if (response.data != null && response.data is List) {
|
||||
final licenses = (response.data as List)
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
final licenses = (response.data['data'] as List)
|
||||
.map((json) => ExpiringLicense.fromJson(json))
|
||||
.toList();
|
||||
return Right(licenses);
|
||||
} else {
|
||||
return Left(ServerFailure(message: '응답 데이터가 올바르지 않습니다'));
|
||||
final errorMessage = response.data?['error']?['message'] ?? '응답 데이터가 올바르지 않습니다';
|
||||
return Left(ServerFailure(message: errorMessage));
|
||||
}
|
||||
} on DioException catch (e) {
|
||||
return Left(_handleDioError(e));
|
||||
} catch (e) {
|
||||
return Left(ServerFailure(message: '만료 예정 라이선스를 가져오는 중 오류가 발생했습니다'));
|
||||
return Left(ServerFailure(message: '만료 예정 라이선스를 가져오는 중 오류가 발생했습니다: $e'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,7 +115,17 @@ class DashboardRemoteDataSourceImpl implements DashboardRemoteDataSource {
|
||||
return NetworkFailure(message: '서버에 연결할 수 없습니다');
|
||||
case DioExceptionType.badResponse:
|
||||
final statusCode = error.response?.statusCode ?? 0;
|
||||
final message = error.response?.data?['message'] ?? '서버 오류가 발생했습니다';
|
||||
final errorData = error.response?.data;
|
||||
|
||||
// 에러 메시지 추출 개선
|
||||
String message;
|
||||
if (errorData is Map) {
|
||||
message = errorData['error']?['message'] ??
|
||||
errorData['message'] ??
|
||||
'서버 오류가 발생했습니다';
|
||||
} else {
|
||||
message = '서버 오류가 발생했습니다';
|
||||
}
|
||||
|
||||
if (statusCode == 401) {
|
||||
return AuthenticationFailure(message: '인증이 만료되었습니다');
|
||||
@@ -119,6 +134,10 @@ class DashboardRemoteDataSourceImpl implements DashboardRemoteDataSource {
|
||||
} else if (statusCode >= 400 && statusCode < 500) {
|
||||
return ServerFailure(message: message);
|
||||
} else {
|
||||
// 500 에러의 경우 더 자세한 메시지 표시
|
||||
if (message.contains('DATABASE_ERROR')) {
|
||||
return ServerFailure(message: '서버 데이터베이스 오류가 발생했습니다. 관리자에게 문의하세요.');
|
||||
}
|
||||
return ServerFailure(message: '서버 오류가 발생했습니다 ($statusCode)');
|
||||
}
|
||||
case DioExceptionType.cancel:
|
||||
|
||||
@@ -6,6 +6,9 @@ import '../../../../services/auth_service.dart';
|
||||
/// 인증 인터셉터
|
||||
class AuthInterceptor extends Interceptor {
|
||||
AuthService? _authService;
|
||||
final Dio dio;
|
||||
|
||||
AuthInterceptor(this.dio);
|
||||
|
||||
AuthService? get authService {
|
||||
try {
|
||||
@@ -22,22 +25,34 @@ class AuthInterceptor extends Interceptor {
|
||||
RequestOptions options,
|
||||
RequestInterceptorHandler handler,
|
||||
) async {
|
||||
print('[AuthInterceptor] onRequest: ${options.method} ${options.path}');
|
||||
|
||||
// 로그인, 토큰 갱신 요청은 토큰 없이 진행
|
||||
if (_isAuthEndpoint(options.path)) {
|
||||
print('[AuthInterceptor] Auth endpoint detected, skipping token attachment');
|
||||
handler.next(options);
|
||||
return;
|
||||
}
|
||||
|
||||
// 저장된 액세스 토큰 가져오기
|
||||
final service = authService;
|
||||
print('[AuthInterceptor] AuthService available: ${service != null}');
|
||||
|
||||
if (service != null) {
|
||||
final accessToken = await service.getAccessToken();
|
||||
print('[AuthInterceptor] Access token retrieved: ${accessToken != null ? 'Yes (${accessToken.substring(0, 10)}...)' : 'No'}');
|
||||
|
||||
if (accessToken != null) {
|
||||
options.headers['Authorization'] = 'Bearer $accessToken';
|
||||
print('[AuthInterceptor] Authorization header set: Bearer ${accessToken.substring(0, 10)}...');
|
||||
} else {
|
||||
print('[AuthInterceptor] WARNING: No access token available for protected endpoint');
|
||||
}
|
||||
} else {
|
||||
print('[AuthInterceptor] ERROR: AuthService not available from GetIt');
|
||||
}
|
||||
|
||||
print('[AuthInterceptor] Final headers: ${options.headers}');
|
||||
handler.next(options);
|
||||
}
|
||||
|
||||
@@ -46,16 +61,32 @@ class AuthInterceptor extends Interceptor {
|
||||
DioException err,
|
||||
ErrorInterceptorHandler handler,
|
||||
) async {
|
||||
print('[AuthInterceptor] onError: ${err.response?.statusCode} ${err.message}');
|
||||
|
||||
// 401 Unauthorized 에러 처리
|
||||
if (err.response?.statusCode == 401) {
|
||||
// 인증 관련 엔드포인트는 재시도하지 않음
|
||||
if (_isAuthEndpoint(err.requestOptions.path)) {
|
||||
print('[AuthInterceptor] Auth endpoint 401 error, skipping retry');
|
||||
handler.next(err);
|
||||
return;
|
||||
}
|
||||
|
||||
final service = authService;
|
||||
if (service != null) {
|
||||
print('[AuthInterceptor] Attempting token refresh...');
|
||||
// 토큰 갱신 시도
|
||||
final refreshResult = await service.refreshToken();
|
||||
|
||||
final refreshSuccess = refreshResult.fold(
|
||||
(failure) => false,
|
||||
(tokenResponse) => true,
|
||||
(failure) {
|
||||
print('[AuthInterceptor] Token refresh failed: ${failure.message}');
|
||||
return false;
|
||||
},
|
||||
(tokenResponse) {
|
||||
print('[AuthInterceptor] Token refresh successful');
|
||||
return true;
|
||||
},
|
||||
);
|
||||
|
||||
if (refreshSuccess) {
|
||||
@@ -64,13 +95,16 @@ class AuthInterceptor extends Interceptor {
|
||||
final newAccessToken = await service.getAccessToken();
|
||||
|
||||
if (newAccessToken != null) {
|
||||
print('[AuthInterceptor] Retrying request with new token');
|
||||
err.requestOptions.headers['Authorization'] = 'Bearer $newAccessToken';
|
||||
|
||||
final response = await Dio().fetch(err.requestOptions);
|
||||
// dio 인스턴스를 통해 재시도
|
||||
final response = await dio.fetch(err.requestOptions);
|
||||
handler.resolve(response);
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
print('[AuthInterceptor] Request retry failed: $e');
|
||||
// 재시도 실패
|
||||
handler.next(err);
|
||||
return;
|
||||
@@ -78,6 +112,7 @@ class AuthInterceptor extends Interceptor {
|
||||
}
|
||||
|
||||
// 토큰 갱신 실패 시 로그인 화면으로 이동
|
||||
print('[AuthInterceptor] Clearing session due to auth failure');
|
||||
await service.clearSession();
|
||||
// TODO: Navigate to login screen
|
||||
}
|
||||
|
||||
@@ -63,15 +63,42 @@ class ErrorInterceptor extends Interceptor {
|
||||
break;
|
||||
|
||||
case DioExceptionType.unknown:
|
||||
handler.reject(
|
||||
DioException(
|
||||
requestOptions: err.requestOptions,
|
||||
error: ServerException(
|
||||
message: AppConstants.unknownError,
|
||||
// CORS 에러 감지 시도
|
||||
final errorMessage = err.message?.toLowerCase() ?? '';
|
||||
final errorString = err.error?.toString().toLowerCase() ?? '';
|
||||
|
||||
if (errorMessage.contains('cors') || errorString.contains('cors') ||
|
||||
errorMessage.contains('xmlhttprequest') || errorString.contains('xmlhttprequest')) {
|
||||
print('[ErrorInterceptor] CORS 에러 감지됨');
|
||||
print('[ErrorInterceptor] 요청 URL: ${err.requestOptions.uri}');
|
||||
print('[ErrorInterceptor] 에러 메시지: ${err.message}');
|
||||
|
||||
handler.reject(
|
||||
DioException(
|
||||
requestOptions: err.requestOptions,
|
||||
error: NetworkException(
|
||||
message: 'CORS 정책으로 인해 API 접근이 차단되었습니다.\n'
|
||||
'개발 환경에서는 run_web_with_proxy.sh 스크립트를 사용하세요.',
|
||||
),
|
||||
type: err.type,
|
||||
),
|
||||
type: err.type,
|
||||
),
|
||||
);
|
||||
);
|
||||
} else {
|
||||
print('[ErrorInterceptor] 알 수 없는 에러');
|
||||
print('[ErrorInterceptor] 에러 타입: ${err.error?.runtimeType}');
|
||||
print('[ErrorInterceptor] 에러 메시지: ${err.message}');
|
||||
print('[ErrorInterceptor] 에러 내용: ${err.error}');
|
||||
|
||||
handler.reject(
|
||||
DioException(
|
||||
requestOptions: err.requestOptions,
|
||||
error: ServerException(
|
||||
message: AppConstants.unknownError,
|
||||
),
|
||||
type: err.type,
|
||||
),
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -90,8 +117,26 @@ class ErrorInterceptor extends Interceptor {
|
||||
// API 응답에서 에러 메시지 추출
|
||||
if (data != null) {
|
||||
if (data is Map) {
|
||||
message = data['message'] ?? data['error'] ?? message;
|
||||
errors = data['errors'] as Map<String, dynamic>?;
|
||||
// error 필드가 객체인 경우 처리
|
||||
if (data['error'] is Map) {
|
||||
final errorObj = data['error'] as Map<String, dynamic>;
|
||||
message = errorObj['message'] ?? message;
|
||||
// code 필드도 저장 (필요시 사용)
|
||||
final errorCode = errorObj['code'];
|
||||
if (errorCode != null) {
|
||||
errors = {'code': errorCode};
|
||||
}
|
||||
} else {
|
||||
// 일반적인 경우: message 또는 error가 문자열
|
||||
message = data['message'] ??
|
||||
(data['error'] is String ? data['error'] : null) ??
|
||||
message;
|
||||
}
|
||||
|
||||
// errors 필드가 있는 경우
|
||||
if (data['errors'] is Map) {
|
||||
errors = data['errors'] as Map<String, dynamic>?;
|
||||
}
|
||||
} else if (data is String) {
|
||||
message = data;
|
||||
}
|
||||
|
||||
@@ -6,8 +6,11 @@ import 'package:flutter/foundation.dart';
|
||||
class LoggingInterceptor extends Interceptor {
|
||||
@override
|
||||
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
|
||||
// 요청 시간 기록
|
||||
options.extra['requestTime'] = DateTime.now();
|
||||
|
||||
debugPrint('╔════════════════════════════════════════════════════════════');
|
||||
debugPrint('║ REQUEST');
|
||||
debugPrint('║ REQUEST [${DateTime.now().toIso8601String()}]');
|
||||
debugPrint('╟────────────────────────────────────────────────────────────');
|
||||
debugPrint('║ ${options.method} ${options.uri}');
|
||||
debugPrint('╟────────────────────────────────────────────────────────────');
|
||||
@@ -42,6 +45,10 @@ class LoggingInterceptor extends Interceptor {
|
||||
}
|
||||
}
|
||||
|
||||
debugPrint('║ Timeout Settings:');
|
||||
debugPrint('║ Connect: ${options.connectTimeout}');
|
||||
debugPrint('║ Receive: ${options.receiveTimeout}');
|
||||
debugPrint('║ Send: ${options.sendTimeout}');
|
||||
debugPrint('╚════════════════════════════════════════════════════════════');
|
||||
|
||||
handler.next(options);
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
/// API 응답을 정규화하는 인터셉터
|
||||
///
|
||||
/// 서버 응답 형식에 관계없이 일관된 형태로 데이터를 처리할 수 있도록 함
|
||||
class ResponseInterceptor extends Interceptor {
|
||||
@override
|
||||
void onResponse(Response response, ResponseInterceptorHandler handler) {
|
||||
print('[ResponseInterceptor] 응답 수신: ${response.requestOptions.path}');
|
||||
print('[ResponseInterceptor] 상태 코드: ${response.statusCode}');
|
||||
print('[ResponseInterceptor] 응답 데이터 타입: ${response.data.runtimeType}');
|
||||
|
||||
// 장비 관련 API 응답 상세 로깅
|
||||
if (response.requestOptions.path.contains('equipment')) {
|
||||
print('[ResponseInterceptor] 장비 API 응답 전체: ${response.data}');
|
||||
if (response.data is List && (response.data as List).isNotEmpty) {
|
||||
final firstItem = (response.data as List).first;
|
||||
print('[ResponseInterceptor] 첫 번째 장비 상태: ${firstItem['status']}');
|
||||
}
|
||||
}
|
||||
|
||||
// 200 OK 응답만 처리
|
||||
if (response.statusCode == 200 || response.statusCode == 201) {
|
||||
// 응답 데이터가 Map인 경우만 처리
|
||||
if (response.data is Map<String, dynamic>) {
|
||||
final data = response.data as Map<String, dynamic>;
|
||||
|
||||
// 이미 정규화된 형식인지 확인
|
||||
if (data.containsKey('success') && data.containsKey('data')) {
|
||||
print('[ResponseInterceptor] 이미 정규화된 응답 형식');
|
||||
handler.next(response);
|
||||
return;
|
||||
}
|
||||
|
||||
// API 응답이 직접 데이터를 반환하는 경우
|
||||
// (예: {accessToken: "...", refreshToken: "...", user: {...}})
|
||||
if (_isDirectDataResponse(data)) {
|
||||
print('[ResponseInterceptor] 직접 데이터 응답을 정규화된 형식으로 변환');
|
||||
|
||||
// 정규화된 응답으로 변환
|
||||
response.data = {
|
||||
'success': true,
|
||||
'data': data,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
handler.next(response);
|
||||
}
|
||||
|
||||
/// 직접 데이터 응답인지 확인
|
||||
bool _isDirectDataResponse(Map<String, dynamic> data) {
|
||||
// 로그인 응답 패턴
|
||||
if (data.containsKey('accessToken') ||
|
||||
data.containsKey('access_token') ||
|
||||
data.containsKey('token')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 사용자 정보 응답 패턴
|
||||
if (data.containsKey('user') ||
|
||||
data.containsKey('id') && data.containsKey('email')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 리스트 응답 패턴
|
||||
if (data.containsKey('items') ||
|
||||
data.containsKey('results') ||
|
||||
data.containsKey('data') && data['data'] is List) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 그 외 일반적인 데이터 응답
|
||||
// success, error, message 등의 메타 키가 없으면 데이터 응답으로 간주
|
||||
final metaKeys = ['success', 'error', 'status', 'code'];
|
||||
final hasMetaKey = metaKeys.any((key) => data.containsKey(key));
|
||||
|
||||
return !hasMetaKey;
|
||||
}
|
||||
}
|
||||
@@ -62,7 +62,13 @@ class LicenseRemoteDataSourceImpl implements LicenseRemoteDataSource {
|
||||
queryParameters: queryParams,
|
||||
);
|
||||
|
||||
return LicenseListResponseDto.fromJson(response.data);
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
return LicenseListResponseDto.fromJson(response.data['data']);
|
||||
} else {
|
||||
throw ApiException(
|
||||
message: response.data?['error']?['message'] ?? 'Failed to fetch licenses',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
throw _handleError(e);
|
||||
}
|
||||
@@ -75,7 +81,13 @@ class LicenseRemoteDataSourceImpl implements LicenseRemoteDataSource {
|
||||
'${ApiEndpoints.licenses}/$id',
|
||||
);
|
||||
|
||||
return LicenseDto.fromJson(response.data);
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
return LicenseDto.fromJson(response.data['data']);
|
||||
} else {
|
||||
throw ApiException(
|
||||
message: response.data?['error']?['message'] ?? 'Failed to fetch license',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
throw _handleError(e);
|
||||
}
|
||||
@@ -89,7 +101,13 @@ class LicenseRemoteDataSourceImpl implements LicenseRemoteDataSource {
|
||||
data: request.toJson(),
|
||||
);
|
||||
|
||||
return LicenseDto.fromJson(response.data);
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
return LicenseDto.fromJson(response.data['data']);
|
||||
} else {
|
||||
throw ApiException(
|
||||
message: response.data?['error']?['message'] ?? 'Failed to fetch license',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
throw _handleError(e);
|
||||
}
|
||||
@@ -103,7 +121,13 @@ class LicenseRemoteDataSourceImpl implements LicenseRemoteDataSource {
|
||||
data: request.toJson(),
|
||||
);
|
||||
|
||||
return LicenseDto.fromJson(response.data);
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
return LicenseDto.fromJson(response.data['data']);
|
||||
} else {
|
||||
throw ApiException(
|
||||
message: response.data?['error']?['message'] ?? 'Failed to fetch license',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
throw _handleError(e);
|
||||
}
|
||||
@@ -128,7 +152,13 @@ class LicenseRemoteDataSourceImpl implements LicenseRemoteDataSource {
|
||||
data: request.toJson(),
|
||||
);
|
||||
|
||||
return LicenseDto.fromJson(response.data);
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
return LicenseDto.fromJson(response.data['data']);
|
||||
} else {
|
||||
throw ApiException(
|
||||
message: response.data?['error']?['message'] ?? 'Failed to fetch license',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
throw _handleError(e);
|
||||
}
|
||||
@@ -141,7 +171,13 @@ class LicenseRemoteDataSourceImpl implements LicenseRemoteDataSource {
|
||||
'${ApiEndpoints.licenses}/$id/unassign',
|
||||
);
|
||||
|
||||
return LicenseDto.fromJson(response.data);
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
return LicenseDto.fromJson(response.data['data']);
|
||||
} else {
|
||||
throw ApiException(
|
||||
message: response.data?['error']?['message'] ?? 'Failed to fetch license',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
throw _handleError(e);
|
||||
}
|
||||
@@ -165,7 +201,13 @@ class LicenseRemoteDataSourceImpl implements LicenseRemoteDataSource {
|
||||
queryParameters: queryParams,
|
||||
);
|
||||
|
||||
return ExpiringLicenseListDto.fromJson(response.data);
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
return ExpiringLicenseListDto.fromJson(response.data['data']);
|
||||
} else {
|
||||
throw ApiException(
|
||||
message: response.data?['error']?['message'] ?? 'Failed to fetch expiring licenses',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
throw _handleError(e);
|
||||
}
|
||||
|
||||
@@ -32,7 +32,13 @@ class UserRemoteDataSource {
|
||||
queryParameters: queryParams,
|
||||
);
|
||||
|
||||
return UserListDto.fromJson(response.data);
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
return UserListDto.fromJson(response.data['data']);
|
||||
} else {
|
||||
throw ApiException(
|
||||
message: response.data?['error']?['message'] ?? '사용자 목록을 불러오는데 실패했습니다',
|
||||
);
|
||||
}
|
||||
} on DioException catch (e) {
|
||||
throw ApiException(
|
||||
message: e.response?.data['message'] ?? '사용자 목록을 불러오는데 실패했습니다',
|
||||
@@ -45,7 +51,13 @@ class UserRemoteDataSource {
|
||||
Future<UserDto> getUser(int id) async {
|
||||
try {
|
||||
final response = await _apiClient.get('/users/$id');
|
||||
return UserDto.fromJson(response.data);
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
return UserDto.fromJson(response.data['data']);
|
||||
} else {
|
||||
throw ApiException(
|
||||
message: response.data?['error']?['message'] ?? '사용자 정보를 불러오는데 실패했습니다',
|
||||
);
|
||||
}
|
||||
} on DioException catch (e) {
|
||||
throw ApiException(
|
||||
message: e.response?.data['message'] ?? '사용자 정보를 불러오는데 실패했습니다',
|
||||
@@ -62,7 +74,13 @@ class UserRemoteDataSource {
|
||||
data: request.toJson(),
|
||||
);
|
||||
|
||||
return UserDto.fromJson(response.data);
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
return UserDto.fromJson(response.data['data']);
|
||||
} else {
|
||||
throw ApiException(
|
||||
message: response.data?['error']?['message'] ?? '사용자 정보를 불러오는데 실패했습니다',
|
||||
);
|
||||
}
|
||||
} on DioException catch (e) {
|
||||
throw ApiException(
|
||||
message: e.response?.data['message'] ?? '사용자 생성에 실패했습니다',
|
||||
@@ -79,7 +97,13 @@ class UserRemoteDataSource {
|
||||
data: request.toJson(),
|
||||
);
|
||||
|
||||
return UserDto.fromJson(response.data);
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
return UserDto.fromJson(response.data['data']);
|
||||
} else {
|
||||
throw ApiException(
|
||||
message: response.data?['error']?['message'] ?? '사용자 정보를 불러오는데 실패했습니다',
|
||||
);
|
||||
}
|
||||
} on DioException catch (e) {
|
||||
throw ApiException(
|
||||
message: e.response?.data['message'] ?? '사용자 정보 수정에 실패했습니다',
|
||||
@@ -108,7 +132,13 @@ class UserRemoteDataSource {
|
||||
data: request.toJson(),
|
||||
);
|
||||
|
||||
return UserDto.fromJson(response.data);
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
return UserDto.fromJson(response.data['data']);
|
||||
} else {
|
||||
throw ApiException(
|
||||
message: response.data?['error']?['message'] ?? '사용자 정보를 불러오는데 실패했습니다',
|
||||
);
|
||||
}
|
||||
} on DioException catch (e) {
|
||||
throw ApiException(
|
||||
message: e.response?.data['message'] ?? '사용자 상태 변경에 실패했습니다',
|
||||
@@ -173,7 +203,13 @@ class UserRemoteDataSource {
|
||||
queryParameters: queryParams,
|
||||
);
|
||||
|
||||
return UserListDto.fromJson(response.data);
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
return UserListDto.fromJson(response.data['data']);
|
||||
} else {
|
||||
throw ApiException(
|
||||
message: response.data?['error']?['message'] ?? '사용자 목록을 불러오는데 실패했습니다',
|
||||
);
|
||||
}
|
||||
} on DioException catch (e) {
|
||||
throw ApiException(
|
||||
message: e.response?.data['message'] ?? '사용자 검색에 실패했습니다',
|
||||
|
||||
@@ -51,7 +51,25 @@ class WarehouseRemoteDataSourceImpl implements WarehouseRemoteDataSource {
|
||||
queryParameters: queryParams,
|
||||
);
|
||||
|
||||
return WarehouseLocationListDto.fromJson(response.data);
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
// API 응답 구조를 DTO에 맞게 변환
|
||||
final List<dynamic> dataList = response.data['data'];
|
||||
final pagination = response.data['pagination'] ?? {};
|
||||
|
||||
final listData = {
|
||||
'items': dataList,
|
||||
'total': pagination['total'] ?? 0,
|
||||
'page': pagination['page'] ?? 1,
|
||||
'per_page': pagination['per_page'] ?? 20,
|
||||
'total_pages': pagination['total_pages'] ?? 1,
|
||||
};
|
||||
|
||||
return WarehouseLocationListDto.fromJson(listData);
|
||||
} else {
|
||||
throw ApiException(
|
||||
message: response.data?['error']?['message'] ?? 'Failed to fetch warehouse locations',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
throw _handleError(e);
|
||||
}
|
||||
@@ -64,7 +82,13 @@ class WarehouseRemoteDataSourceImpl implements WarehouseRemoteDataSource {
|
||||
'${ApiEndpoints.warehouseLocations}/$id',
|
||||
);
|
||||
|
||||
return WarehouseLocationDto.fromJson(response.data);
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
return WarehouseLocationDto.fromJson(response.data['data']);
|
||||
} else {
|
||||
throw ApiException(
|
||||
message: response.data?['error']?['message'] ?? 'Failed to fetch warehouse location',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
throw _handleError(e);
|
||||
}
|
||||
@@ -78,7 +102,13 @@ class WarehouseRemoteDataSourceImpl implements WarehouseRemoteDataSource {
|
||||
data: request.toJson(),
|
||||
);
|
||||
|
||||
return WarehouseLocationDto.fromJson(response.data);
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
return WarehouseLocationDto.fromJson(response.data['data']);
|
||||
} else {
|
||||
throw ApiException(
|
||||
message: response.data?['error']?['message'] ?? 'Failed to fetch warehouse location',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
throw _handleError(e);
|
||||
}
|
||||
@@ -92,7 +122,13 @@ class WarehouseRemoteDataSourceImpl implements WarehouseRemoteDataSource {
|
||||
data: request.toJson(),
|
||||
);
|
||||
|
||||
return WarehouseLocationDto.fromJson(response.data);
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
return WarehouseLocationDto.fromJson(response.data['data']);
|
||||
} else {
|
||||
throw ApiException(
|
||||
message: response.data?['error']?['message'] ?? 'Failed to fetch warehouse location',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
throw _handleError(e);
|
||||
}
|
||||
@@ -126,7 +162,13 @@ class WarehouseRemoteDataSourceImpl implements WarehouseRemoteDataSource {
|
||||
queryParameters: queryParams,
|
||||
);
|
||||
|
||||
return WarehouseEquipmentListDto.fromJson(response.data);
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
return WarehouseEquipmentListDto.fromJson(response.data['data']);
|
||||
} else {
|
||||
throw ApiException(
|
||||
message: response.data?['error']?['message'] ?? 'Failed to fetch warehouse equipment',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
throw _handleError(e);
|
||||
}
|
||||
@@ -139,7 +181,13 @@ class WarehouseRemoteDataSourceImpl implements WarehouseRemoteDataSource {
|
||||
'${ApiEndpoints.warehouseLocations}/$id/capacity',
|
||||
);
|
||||
|
||||
return WarehouseCapacityInfo.fromJson(response.data);
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
|
||||
return WarehouseCapacityInfo.fromJson(response.data['data']);
|
||||
} else {
|
||||
throw ApiException(
|
||||
message: response.data?['error']?['message'] ?? 'Failed to fetch warehouse capacity',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
throw _handleError(e);
|
||||
}
|
||||
@@ -152,8 +200,8 @@ class WarehouseRemoteDataSourceImpl implements WarehouseRemoteDataSource {
|
||||
'${ApiEndpoints.warehouseLocations}/in-use',
|
||||
);
|
||||
|
||||
if (response.data is List) {
|
||||
return (response.data as List)
|
||||
if (response.data != null && response.data['success'] == true && response.data['data'] is List) {
|
||||
return (response.data['data'] as List)
|
||||
.map((item) => WarehouseLocationDto.fromJson(item))
|
||||
.toList();
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user