AppResponse<T>.fromJson constructor

AppResponse<T>.fromJson(
  1. Map<String, dynamic> json, {
  2. T dataParser(
    1. dynamic json
    )?,
})

Maps a raw JSON Map into the appropriate AppResponse subtype.

The logic determines the type based on the presence of the status field and the value of statusCode.

An optional dataParser can be provided to transform the data field into a specific model T.

Implementation

factory AppResponse.fromJson(
  Map<String, dynamic> json, {
  T Function(dynamic json)? dataParser,
}) {
  /// --- ACTION RESPONSE (no status field) ---
  /// Typically used for intermediate steps or specialized triggers.
  if (!json.containsKey('status')) {
    return ActionResponse<T>(
      code: json['code'] as String,
      action: json['action'] as String,
      message: json['message'] as String,
    );
  }

  final bool status = json['status'] as bool;
  final int statusCode = json['statusCode'] as int;
  final String message = json['message']?.toString() ?? '';
  final dynamic dataJson = json['data'];
  final String error = json['error']?.toString() ?? '';

  /// --- ERROR RESPONSE ---
  /// Triggered if the status is false or the HTTP status code indicates a failure.
  if (status == false || statusCode >= 400) {
    return ErrorResponse<T>(
      status: status,
      statusCode: statusCode,
      message: message,
      error: error.isNotEmpty ? error : message,
      data: _parseNullableData<T>(dataJson, dataParser),
    );
  }

  /// --- SUCCESS RESPONSE ---
  /// Standard successful result containing the requested data.
  return SuccessResponse<T>(
    status: status,
    statusCode: statusCode,
    message: message,
    data: _parseData<T>(dataJson, dataParser),
    error: error,
  );
}