createApiNetworkingLayerCode function

void createApiNetworkingLayerCode()

Implementation

void createApiNetworkingLayerCode() {
  // Create api_networking_layer.dart in lib/core/network
  final networking = File('lib/core/network/api_networking_layer.dart');
  if (!networking.existsSync()) {
    networking.writeAsStringSync('''
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';

enum RequestType { GET, POST, PUT, PATCH, DELETE }

class ApiNetworkingLayer {
  late final Dio _dio;

 /// Default timeout (ms)
  int get _timeoutDuration => 5000;

  ApiNetworkingLayer() {
    _dio = Dio(
      BaseOptions(
        baseUrl: Env.baseURL,
        connectTimeout: Duration(milliseconds: _timeoutDuration),
        receiveTimeout: Duration(milliseconds: _timeoutDuration),
      ),
   );
    // _dio.interceptors.add(RefreshTokenInterceptor()); // interceptor if any
  }

  /// Main request method
  Future<ApiResponseGeneric> makeRequest<T>(
    RequestType type, {
    dynamic body,
    bool hasToken = false,
    required String urlExt,
  }) async {
    final Options options = _generateOptions(type.name, hasToken);

    return await _dioRequest<T>(options, body: body, urlExt: urlExt);
  }

  Future<ApiResponseGeneric> _dioRequest<T>(Options options, {dynamic body, required String urlExt}) async {
    try {
      Response response = await _dio.request<T>(Env.baseURL + urlExt, data: body, options: options).timeout(
            Duration(milliseconds: _timeoutDuration),
          );

      return ApiResponseGeneric.fromResponse(response);
    } catch (e) {
      return CustomExceptionHandler.handleException(e);
    }
  }

  Options _generateOptions(String method, bool hasToken) {
    Map<String, String> headers = {};

    if (hasToken) {
      headers['Authorization'] = AuthService.accessToken; // stub
    }

    return Options(
      method: method,
      headers: headers,
      contentType: Headers.jsonContentType,
    );
  }
}

/// Exception handler (stub – extend later)
class CustomExceptionHandler {
  static ApiResponseGeneric handleException(dynamic error) {
    return ApiResponseGeneric(
      statusCode: 500,
      data: {'error': error.toString()},
    );
  }
}
''');
  }
}