initializeAppstraxServices function

Future<void> initializeAppstraxServices({
  1. required String apiUrl,
  2. required String apiKey,
  3. Client? httpClient,
  4. Duration timeout = HttpService.defaultTimeout,
  5. Duration uploadTimeout = HttpService.defaultUploadTimeout,
  6. void onRestoreError(
    1. Object error,
    2. StackTrace stackTrace
    )?,
})

Configures the SDK and restores any saved session. Call this once, before anything else.

apiUrl must use https outside local development, since every request carries a password or a token.

httpClient replaces the client used for every request, which is where an application supplies certificate pinning, a proxy, or request logging. It is wrapped for retries and closed by whoever created it, not by the SDK.

timeout bounds a single request, retries included.

uploadTimeout bounds a file upload instead, both the send and the read of the response. Separate from timeout because thirty seconds is generous for a JSON call and far too short for a large file on a mobile connection.

onRestoreError is called if a saved session could not be restored. Restoring is never allowed to throw - an exception here would fail app startup, on this launch and every later one - so this is the only way to see that it happened.

Implementation

Future<void> initializeAppstraxServices({
  required String apiUrl,
  required String apiKey,
  http.Client? httpClient,
  Duration timeout = HttpService.defaultTimeout,
  Duration uploadTimeout = HttpService.defaultUploadTimeout,
  void Function(Object error, StackTrace stackTrace)? onRestoreError,
}) async {
  Config().initialize(apiUrl: apiUrl, apiKey: apiKey);

  // The one place the transport is composed. The token provider is a function
  // so that http.dart does not have to import the auth service, which would
  // make each of them impossible to construct without the other.
  final httpService = HttpService(
    client: buildRetryingClient(httpClient ?? http.Client()),
    // The retrying client is a wrapper either way, so it cannot tell whose
    // socket is underneath. Only here knows: an injected client belongs to the
    // application and must outlive the SDK.
    ownsClient: httpClient == null,
    tokenProvider: () => appstraxAuth.getAuthToken(),
    timeout: timeout,
    uploadTimeout: uploadTimeout,
  );

  appstraxAuth.http = httpService;
  appstraxDb.http = httpService;
  appstraxStorage.http = httpService;
  appstraxAuth.onRestoreError = onRestoreError;

  await SecureStorageService().initialize();
  await appstraxAuth.initialize();
}