request method
Future<ResponseModel>
request({
- required RequestType requestType,
- required String path,
- String? param,
- QueryModel? query,
- BodyDataModel? data,
- ContentType? contentType,
Makes a request.
This method makes a request of the specified type to the specified path. It can optionally include a parameter, a query model, a body data model, and a content type. It returns a ResponseModel that represents the response from the server.
Implementation
Future<ResponseModel> request({
required RequestType requestType,
required String path,
String? param,
QueryModel? query,
BodyDataModel? data,
ContentType? contentType,
}) async {
switch (contentType) {
case ContentType.json:
_dio!.options.contentType = "application/json";
break;
case ContentType.multipart:
_dio!.options.contentType = "multipart/form-data";
break;
default:
_dio!.options.contentType = "application/json";
break;
}
try {
Response? response;
Map<String, dynamic>? filteredData;
FormData? formData = await data?.toFormData();
if (data != null && formData == null) {
final postData = data.toPostJson();
final putData = data.toPutJson();
if (postData != null) {
postData.removeWhere((key, value) => value == null || value == "");
}
if (putData != null) {
putData.removeWhere((key, value) => value == null || value == "");
}
if (requestType == RequestType.post) {
filteredData = postData;
} else if (requestType == RequestType.put) {
filteredData = putData;
}
}
Map<String, dynamic>? filteredQuery;
if (query != null) {
final queryData = query.toJson();
queryData.removeWhere((key, value) => value == null || value == "");
filteredQuery = queryData;
}
switch (requestType) {
case RequestType.get:
response = await _dio!.get(
"$path/${param ?? ""}",
queryParameters: filteredQuery,
);
break;
case RequestType.post:
response = await _dio!.post(
"$path/${param ?? ""}",
data: formData ?? filteredData,
queryParameters: filteredQuery,
);
break;
case RequestType.put:
response = await _dio!.put(
"$path/${param ?? ""}",
data: formData ?? filteredData,
queryParameters: filteredQuery,
);
break;
case RequestType.delete:
response = await _dio!.delete(
"$path/${param ?? ""}",
queryParameters: filteredQuery,
);
break;
}
return ResponseModel.fromJson(response.data);
} catch (e) {
if (e is DioException) {
return ResponseModel(
statusCode: 999,
message: e.message,
);
} else {
return ResponseModel(
statusCode: 999,
message: "Unexpected error occured.",
data: e,
);
}
}
}