invoice/lib/data/web_client.dart

92 lines
2.0 KiB
Dart

import 'dart:async';
import 'dart:core';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:invoiceninja/constants.dart';
class WebClient {
const WebClient();
String _parseError(String response) {
String error = response;
try {
final dynamic jsonResponse = json.decode(response);
error = jsonResponse['error'] ?? jsonResponse;
} catch(error) {
// do nothing
}
return error;
}
Future<dynamic> get(String url, String token) async {
if (! url.contains('?')) url += '?';
url += '&per_page=$kMaxRecordsPerApiPage';
final http.Response response = await http.Client().get(
url,
headers: {
'X-Ninja-Token': token,
},
);
if (response.statusCode >= 400) {
throw _parseError(response.body);
}
final dynamic jsonResponse = json.decode(response.body);
//print(jsonResponse);
return jsonResponse;
}
Future<dynamic> post(String url, String token, dynamic data) async {
final http.Response response = await http.Client().post(
url,
body: data,
headers: {
'X-Ninja-Token': token,
'Content-Type': 'application/json',
},
);
if (response.statusCode >= 400) {
throw _parseError(response.body);
}
try {
final dynamic jsonResponse = json.decode(response.body);
return jsonResponse;
} catch (exception) {
print(response.body);
throw('An error occurred');
}
}
Future<dynamic> put(String url, String token, dynamic data) async {
final http.Response response = await http.Client().put(
url,
body: data,
headers: {
'X-Ninja-Token': token,
'Content-Type': 'application/json',
},
);
if (response.statusCode >= 400) {
throw _parseError(response.body);
}
try {
final dynamic jsonResponse = json.decode(response.body);
return jsonResponse;
} catch (exception) {
print(response.body);
throw('An error occurred');
}
}
}