// SPDX-License-Identifier: AGPL-3.0-or-later import 'dart:convert'; import 'package:http/http.dart' as http; import 'generated/models.dart'; export 'generated/models.dart'; /// Minimal docwell-server client. Requests are written by hand; the models /// are generated from api/openapi.yaml (tool/generate_api.dart). class DocwellApi { DocwellApi(String baseUrl, {http.Client? client}) : baseUrl = baseUrl.replaceAll(RegExp(r'/+$'), ''), _client = client ?? http.Client(); final String baseUrl; final http.Client _client; /// PocketBase auth token of the signed-in user, sent as a bearer token. String? token; Future version() async { final body = await _send('GET', '/api/v1/version'); return body['version'] as String; } /// Signs in with email and password and keeps the token for later calls. Future login(String email, String password) async { final body = await _send('POST', '/api/v1/auth/login', { 'email': email, 'password': password, }); token = body['token'] as String; return User.fromJson(body['user'] as Map); } Future me() async => User.fromJson(await _send('GET', '/api/v1/auth/me')); void logout() => token = null; Future> _send( String method, String path, [ Object? body, ]) async { final req = http.Request(method, Uri.parse('$baseUrl$path')); req.headers['Accept'] = 'application/json'; if (token != null) req.headers['Authorization'] = 'Bearer $token'; if (body != null) { req.headers['Content-Type'] = 'application/json'; req.body = jsonEncode(body); } final res = await http.Response.fromStream( await _client.send(req).timeout(const Duration(seconds: 15)), ); final data = res.body.isEmpty ? {} : jsonDecode(res.body) as Map; if (res.statusCode >= 300) { throw DocwellApiException( res.statusCode, data['error'] as String? ?? 'unknown', ); } return data; } } extension UserRoles on User { /// Admins manage their organization; superadmins manage everything. bool get isManager => role == Role.admin || role == Role.superadmin; } class DocwellApiException implements Exception { DocwellApiException(this.status, [this.code = 'unknown']); final int status; /// Machine-readable error code from the server, e.g. "invalid_credentials". final String code; @override String toString() => 'Docwell API error $status ($code)'; }