Line data Source code
1 : import 'dart:convert';
2 : import 'package:flutter/foundation.dart';
3 : import '../worker.dart';
4 :
5 : export 'request_signing.dart';
6 :
7 : /// HTTP sync worker configuration.
8 : @immutable
9 : final class HttpSyncWorker extends Worker {
10 9 : const HttpSyncWorker({
11 : required this.url,
12 : this.method = HttpMethod.post,
13 : this.headers = const {},
14 : this.requestBody,
15 : this.timeout = const Duration(seconds: 60),
16 : this.requestSigning,
17 : this.tokenRefresh,
18 : });
19 :
20 : final String url;
21 : final HttpMethod method;
22 : final Map<String, String> headers;
23 : final Map<String, dynamic>? requestBody;
24 : final Duration timeout;
25 :
26 : /// HMAC-SHA256 request signing configuration.
27 : ///
28 : /// When set, each sync request is signed with the specified secret key and
29 : /// the signature is injected as a request header (default: `X-Signature`).
30 : final RequestSigning? requestSigning;
31 :
32 : /// Automatic token refresh configuration.
33 : final TokenRefreshConfig? tokenRefresh;
34 :
35 4 : @override
36 : String get workerClassName => 'HttpSyncWorker';
37 :
38 5 : @override
39 : Map<String, dynamic> toMap() {
40 : // NET-016: validate requestBody is JSON-serializable before the task is
41 : // dispatched to the native layer. jsonEncode already throws on circular
42 : // references / non-serializable objects, but wrapping with a clear message
43 : // avoids a cryptic JsonUnsupportedObjectError at enqueue time.
44 : String? encodedBody;
45 5 : if (requestBody != null) {
46 : try {
47 8 : encodedBody = jsonEncode(requestBody);
48 2 : } on JsonUnsupportedObjectError catch (e) {
49 2 : throw ArgumentError(
50 2 : 'HttpSyncWorker.requestBody must be JSON-serializable: $e',
51 : );
52 : }
53 : }
54 5 : return {
55 5 : 'workerType': 'httpSync',
56 10 : 'url': url,
57 15 : 'method': method.name,
58 10 : 'headers': headers,
59 5 : 'requestBody': encodedBody,
60 15 : 'timeoutMs': timeout.inMilliseconds,
61 8 : if (requestSigning != null) 'requestSigning': requestSigning!.toMap(),
62 8 : if (tokenRefresh != null) 'tokenRefresh': tokenRefresh!.toMap(),
63 : };
64 : }
65 : }
|