Skip to content

Instantly share code, notes, and snippets.

@snghnishant
Created October 5, 2023 13:20
Show Gist options
  • Save snghnishant/fdc1da72019fbdddf316666fefbcbbfc to your computer and use it in GitHub Desktop.
Save snghnishant/fdc1da72019fbdddf316666fefbcbbfc to your computer and use it in GitHub Desktop.
API wrapper
import 'dart:async';
import 'dart:convert';
import 'package:firebase_performance/firebase_performance.dart';
import 'package:http/http.dart' as http;
import '../../logger_service.dart';
import '../../httpClient.dart'; // API_BASE_URL in this file
enum RequestType { GET, POST, DELETE, PUT }
class APIService {
static const PROD_URL = 'https://myprodurl.com'; // Prod
static Future<Map<String, dynamic>> sendRequest(
String endpoint,
RequestType requestType,
Map<String, dynamic>? data,
Map<String, String>? headers,
) async {
Map<String, dynamic>? decodedData;
try {
final token = getUserToken(); // gets me the auth token if any
final dHeader = {'authorization': 'Bearer $token'}; // JWT auth
if (token == '') throw 'Empty request token';
http.Response? response;
if (requestType == RequestType.GET) {
response = await http
.get(
Uri.parse(API_BASE_URL + endpoint),
headers: headers ?? dHeader,
)
.timeout(
const Duration(seconds: 15),
);
} else if (requestType == RequestType.DELETE) {
response = await http
.delete(
Uri.parse(API_BASE_URL + endpoint),
headers: headers ?? dHeader,
body: data,
)
.timeout(
const Duration(seconds: 15),
);
} else if (requestType == RequestType.PUT) {
response = await http
.put(
Uri.parse(API_BASE_URL + endpoint),
headers: headers ?? dHeader,
body: data,
)
.timeout(
const Duration(seconds: 15),
);
} else {
response = await http
.post(
Uri.parse(API_BASE_URL + endpoint),
headers: headers ?? dHeader,
body: data,
)
.timeout(
const Duration(seconds: 15),
);
}
if (response.statusCode == 401 && API_BASE_URL == PROD_URL) {
// run some function to logout user from app
// logoutUser()
throw 'Session Expired';
} else if (response.statusCode == 429) {
throw 'Too many requests, please try again later!';
} else {
try {
decodedData = jsonDecode(response.body);
} catch (err) {
Logger.log(err.toString());
}
String? message = decodedData?['message'] ?? decodedData?['status'];
if (response.statusCode == 400) {
if (message != null)
throw message;
else
throw 'Invalid Request';
} else if (response.statusCode != 200 && response.statusCode != 201) {
if (message != null)
throw 'Internal Server Error: $message';
else
throw 'Internal Server Error';
}
return decodedData!;
}
} on TimeoutException catch (e) {
Logger.log(e.toString());
return decodedData ?? {'success': false, 'message': 'Request Timeout'};
} catch (e) {
Logger.log(endpoint);
Logger.log(e.toString());
return decodedData ?? {'success': false, 'message': e.toString()};
}
}
static Future<Map<String, dynamic>> sendPublicRequest(
String endpoint,
RequestType requestType,
Map<String, String> data,
Map<String, String>? headers,
) async {
Map<String, dynamic>? decodedData;
try {
http.Response response;
if (requestType == RequestType.GET) {
response = await http.get(Uri.parse(API_BASE_URL + endpoint)).timeout(
const Duration(seconds: 15),
);
} else {
response = await http
.post(Uri.parse(API_BASE_URL + endpoint),
body: data, headers: headers)
.timeout(
const Duration(seconds: 15),
);
}
if (response.statusCode == 429) {
throw 'Too many requests, please try again later!';
// Or throw error body message from api
}
if (response.statusCode != 200) {
throw 'Internal Server Error';
// Or throw error body message from api
}
decodedData = jsonDecode(response.body);
return decodedData!;
} on TimeoutException catch (e) {
Logger.log(e.toString());
return decodedData ?? {'success': false, 'message': 'Request Timeout'};
} catch (e) {
Logger.log(e.toString());
return decodedData ?? {'success': false, 'message': 'Server error'};
}
}
static HttpMethod getRequestType(RequestType requestType) {
return requestType == RequestType.GET
? HttpMethod.Get
: requestType == RequestType.POST
? HttpMethod.Post
: requestType == RequestType.PUT
? HttpMethod.Put
: HttpMethod.Delete;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment