pullSecrets method

Future<Map<String, String>> pullSecrets({
  1. String? projectRef,
  2. String? environmentSlug,
  3. bool fallbackOnError = true,
})

Returns all secrets for an environment merged into a flat Map<String, String>.

In API key mode: project + environment are auto-discovered via getKeyContext. In JWT mode: pass projectRef + environmentSlug explicitly, or set BELLA_BAXTER_PROJECT / BELLA_BAXTER_ENV env vars.

This is the primary method for secret consumption — equivalent to bella pull.

When fallbackOnError is true (default) and the request fails (e.g. no network, timeout, invalid credentials), an empty map is returned instead of throwing. Set to false if you need to handle errors explicitly.

Implementation

Future<Map<String, String>> pullSecrets({
  String? projectRef,
  String? environmentSlug,
  bool fallbackOnError = true,
}) async {
  try {
    String resolvedProject = projectRef ?? '';
    String resolvedEnv = environmentSlug ?? '';

    if (resolvedProject.isEmpty || resolvedEnv.isEmpty) {
      // Try API key context first
      try {
        final ctx = await getKeyContext();
        resolvedProject = resolvedProject.isNotEmpty
            ? resolvedProject
            : (ctx.projectSlug ?? '');
        resolvedEnv = resolvedEnv.isNotEmpty
            ? resolvedEnv
            : (ctx.environmentSlug ?? '');
      } catch (_) {
        // JWT mode: fall back to env vars
        resolvedProject = resolvedProject.isNotEmpty
            ? resolvedProject
            : (Platform.environment['BELLA_BAXTER_PROJECT'] ?? '');
        resolvedEnv = resolvedEnv.isNotEmpty
            ? resolvedEnv
            : (Platform.environment['BELLA_BAXTER_ENV'] ?? '');
      }
    }

    final resp = await _api
        .getBellaBaxterFeaturesProjectsEnvironmentsSecretsGetAllEnvironmentSecretsApi()
        .getAllEnvironmentSecrets(
          projectRef: resolvedProject,
          envSlug: resolvedEnv,
        );
    final data = resp.data;
    if (data == null) return {};
    final result = Map<String, String>.from(data.secrets.toMap());
    // Write-through: persist to cache on every successful fetch.
    await _cache?.write(result);
    return result;
  } catch (e) {
    if (fallbackOnError) {
      // Try the encrypted cache before giving up.
      final cached = await _tryReadCache();
      return cached ?? {};
    }
    rethrow;
  }
}