73 lines
2.2 KiB
Dart
73 lines
2.2 KiB
Dart
import 'dart:convert';
|
||
import 'package:http/http.dart' as http;
|
||
|
||
class AdminRepository {
|
||
AdminRepository({required this.client, required this.baseUrl});
|
||
final http.Client client;
|
||
final String baseUrl;
|
||
Future<Set<String>> permissions() async =>
|
||
((await _get('/me'))['permissions'] as List).cast<String>().toSet();
|
||
Future<Map<String, Object?>> dashboard() async {
|
||
final values = await Future.wait([
|
||
_get('/admin/metrics'),
|
||
_list('/admin/organization/departments'),
|
||
_list('/admin/organization/roles'),
|
||
_list('/admin/organization/users'),
|
||
_list('/admin/workflows/definitions'),
|
||
_list('/admin/workflows/instances'),
|
||
_list('/admin/audit-events?limit=100'),
|
||
]);
|
||
return {
|
||
'metrics': values[0],
|
||
'departments': values[1],
|
||
'roles': values[2],
|
||
'users': values[3],
|
||
'definitions': values[4],
|
||
'instances': values[5],
|
||
'audits': values[6],
|
||
};
|
||
}
|
||
|
||
Future<void> createDepartment(String code, String name) => _write(
|
||
'POST',
|
||
'/admin/organization/departments',
|
||
{'code': code, 'name': name},
|
||
);
|
||
Future<void> replaceRoles(String userId, Set<String> roles) => _write(
|
||
'PUT',
|
||
'/admin/organization/users/$userId/roles',
|
||
{'roles': roles.toList()},
|
||
);
|
||
Future<Map<String, Object?>> _get(String path) async {
|
||
final r = await client.get(Uri.parse('$baseUrl$path'));
|
||
_ok(r);
|
||
return Map<String, Object?>.from(jsonDecode(r.body) as Map);
|
||
}
|
||
|
||
Future<List<Map<String, Object?>>> _list(String path) async {
|
||
final r = await client.get(Uri.parse('$baseUrl$path'));
|
||
_ok(r);
|
||
return (jsonDecode(r.body) as List)
|
||
.map((e) => Map<String, Object?>.from(e as Map))
|
||
.toList();
|
||
}
|
||
|
||
Future<void> _write(
|
||
String method,
|
||
String path,
|
||
Map<String, Object?> body,
|
||
) async {
|
||
final request = http.Request(method, Uri.parse('$baseUrl$path'))
|
||
..headers['Content-Type'] = 'application/json'
|
||
..body = jsonEncode(body);
|
||
final r = await http.Response.fromStream(await client.send(request));
|
||
_ok(r);
|
||
}
|
||
|
||
void _ok(http.Response r) {
|
||
if (r.statusCode < 200 || r.statusCode >= 300) {
|
||
throw Exception('管理请求失败(${r.statusCode})');
|
||
}
|
||
}
|
||
}
|