getDuration method

Duration getDuration(
  1. String key, {
  2. Duration? defaultValue,
})

Implementation

Duration getDuration(String key, {Duration? defaultValue}) {
  final s = _env[key];
  if (s == null) {
    if (defaultValue != null) return defaultValue;
    throw StateError('Missing env "$key"');
  }
  // Supports ISO8601 (e.g. PT15M) or simple "<number><unit>" like "30s", "5m", "2h".
  final v = s.trim();
  if (v.startsWith('P')) {
    // ISO8601
    return _parseIso8601Duration(v);
  }
  final simple = RegExp(r'^(\d+)\s*([smhd])$');
  final m = simple.firstMatch(v);
  if (m != null) {
    final n = int.parse(m.group(1)!);
    switch (m.group(2)!) {
      case 's':
        return Duration(seconds: n);
      case 'm':
        return Duration(minutes: n);
      case 'h':
        return Duration(hours: n);
      case 'd':
        return Duration(days: n);
    }
  }
  throw FormatException('Env "$key" is not a duration: "$s"');
}