actions-test/lib/backend/request.dart

65 lines
1.9 KiB
Dart
Raw Normal View History

2023-03-17 21:06:41 +01:00
import 'package:http/http.dart' as http;
import 'dart:convert';
import './resolve_url.dart';
import './user.dart';
2023-03-17 21:06:41 +01:00
enum Result { ok, err }
2023-03-17 21:06:41 +01:00
class Response {
final Map<String, dynamic> body;
final Result res;
const Response({required this.body, required this.res});
}
Future<Response> usePostApi(
2023-12-22 20:14:36 +01:00
{required OutbagServer target,
2023-03-17 21:06:41 +01:00
String path = '',
required Map<String, String> headers,
required Map<String, dynamic> body}) async {
final resp = await http.post(Uri.parse('${target.base}api/$path'),
2023-12-22 20:14:36 +01:00
headers: headers, body: jsonEncode({'data': body}));
2023-03-17 21:06:41 +01:00
final json = jsonDecode(resp.body);
return Response(
2023-12-22 20:14:36 +01:00
body: json, res: resp.statusCode == 200 ? Result.ok : Result.err);
2023-03-17 21:06:41 +01:00
}
Future<Response> postWithCreadentials(
2023-12-22 20:14:36 +01:00
{required OutbagServer target,
2023-03-17 21:06:41 +01:00
String path = '',
required Map<String, dynamic> body,
required User credentials}) async {
2023-03-17 21:06:41 +01:00
Map<String, String> headers = {
"Content-Type": "application/json",
'Connection': 'keep-alive',
2023-03-17 21:06:41 +01:00
'Authorization':
2023-12-22 20:14:36 +01:00
'Digest name=${credentials.username} server=${target.tag} accountKey=${credentials.password}'
2023-03-17 21:06:41 +01:00
};
return await usePostApi(
2023-12-22 20:14:36 +01:00
target: target, path: path, headers: headers, body: body);
2023-03-17 21:06:41 +01:00
}
Future<Response> postWithToken(
2023-12-22 20:14:36 +01:00
{required OutbagServer target,
2023-03-17 21:06:41 +01:00
String path = '',
required Map<String, dynamic> body,
required String token}) async {
Map<String, String> headers = {
"Content-Type": "application/json",
'Authorization': 'Bearer $token'
};
return await usePostApi(
2023-12-22 20:14:36 +01:00
target: target, path: path, headers: headers, body: body);
2023-03-17 21:06:41 +01:00
}
Future<Response> postUnauthorized(
2023-12-22 20:14:36 +01:00
{required OutbagServer target,
2023-03-17 21:06:41 +01:00
String path = '',
required Map<String, dynamic> body}) async {
Map<String, String> headers = {
"Content-Type": "application/json",
};
return await usePostApi(
2023-12-22 20:14:36 +01:00
target: target, path: path, headers: headers, body: body);
2023-03-17 21:06:41 +01:00
}