Skip to content

Commit

Permalink
fix(logging): use indexedDB on web if it is supported
Browse files Browse the repository at this point in the history
  • Loading branch information
Nika Hassani committed Oct 16, 2023
1 parent d48f1bf commit 6e0d073
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

// ignore_for_file: implementation_imports

import 'dart:async';

import 'package:amplify_core/amplify_core.dart';
import 'package:amplify_logging_cloudwatch/src/queued_item_store/index_db/indexed_db_adapter.dart';
import 'package:aws_logging_cloudwatch/src/queued_item_store/in_memory_queued_item_store.dart';
Expand All @@ -15,18 +17,23 @@ class DartQueuedItemStore
implements QueuedItemStore, Closeable {
/// {@macro amplify_logging_cloudwatch.index_db_queued_item_store}
// ignore: avoid_unused_constructor_parameters
DartQueuedItemStore(String? storagePath);
DartQueuedItemStore(String? storagePath) {
scheduleMicrotask(_init);
}

late final QueuedItemStore _database = () {
if (IndexedDbAdapter.checkIsIndexedDBSupported()) {
return IndexedDbAdapter();
late final QueuedItemStore _database;

Future<void> _init() async {
if (await IndexedDbAdapter.checkIsIndexedDBSupported()) {
_database = IndexedDbAdapter();
return;
}
logger.warn(
'IndexedDB is not available. '
'Falling back to in-memory storage.',
);
return InMemoryQueuedItemStore();
}();
_database = InMemoryQueuedItemStore();
}

@override
String get runtimeTypeName => 'DartQueuedItemStore';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,15 +138,14 @@ class IndexedDbAdapter implements QueuedItemStore {
await request.future;

for (final elem in request.result) {
final value = elem as Map<String, dynamic>;
final id = value['id'] as int;
final itemValue = value['value'] as String;
final timestamp = value['timestamp'] as String;
final value = elem as Object;
final id = getProperty<int>(value, 'id');
final string = getProperty<String>(value, 'value');
final timestamp = getProperty<String>(value, 'timestamp');
readValues.add(
QueuedItem(id: id, value: itemValue, timestamp: timestamp),
QueuedItem(id: id, value: string, timestamp: timestamp),
);
}

return readValues;
}

Expand All @@ -168,14 +167,15 @@ class IndexedDbAdapter implements QueuedItemStore {
void close() {}

/// Check that IndexDB will work on this device.
static bool checkIsIndexedDBSupported() {
static Future<bool> checkIsIndexedDBSupported() async {
if (indexedDB == null) {
return false;
}
// indexedDB will be non-null in Firefox private browsing,
// but will fail to open.
try {
indexedDB!.open('test', 1).result;
final openRequest = indexedDB!.open('test', 1);
await openRequest.future;
return true;
} on Object {
return false;
Expand Down

0 comments on commit 6e0d073

Please sign in to comment.