Skip to content

Instantly share code, notes, and snippets.

@PlugFox
Last active September 17, 2019 15:59
Show Gist options
  • Save PlugFox/a013510572bb2115d6ac2e434cb8d197 to your computer and use it in GitHub Desktop.
Save PlugFox/a013510572bb2115d6ac2e434cb8d197 to your computer and use it in GitHub Desktop.
Repository with local provider
/*
https://gist.github.com/PlugFox/a013510572bb2115d6ac2e434cb8d197
https://dartpad.dartlang.org/a013510572bb2115d6ac2e434cb8d197
*/
import 'dart:html'; // for _LocalProviderStorage
abstract class Repository {
static final RepositoryProvider _repository = RepositoryProvider();
static String get token => _repository.localProvider.token;
static set token(dynamic value) => _repository.localProvider.token = value;
static Map<String,String> get userInfo => _repository.localProvider.userInfo;
static set userInfo(Map<String,String> value) => _repository.localProvider.userInfo = value;
// Это класс возможно использовать только для миксинов, а также дергать его методы напрямую
factory Repository._() => null;
// Эмуляция задержки
static Future<void> emulateDelay({int milliseconds = 500}) async => await Future.delayed(Duration(milliseconds: milliseconds));
}
// Репозиторий
class RepositoryProvider {
final LocalProvider localProvider = LocalProvider();
// СИНГЛТОН +
static final RepositoryProvider _repository = RepositoryProvider._internal();
factory RepositoryProvider() => _repository;
RepositoryProvider._internal() {
print('Создаем синглтон RepositoryProvider');
}
// СИНГЛТОН -
}
class LocalProvider {
LocalProvider();
final _LocalProviderStorage _store = _LocalProviderStorage();
String get token => this._store['token'];
set token(dynamic value) => this._store['token'] = value;
Map<String,String> get userInfo =>
<String, String>{}
..['token'] = this._store['token']
..['name'] = this._store['name']
..['email'] = this._store['email']
..['avatar'] = this._store['avatar'];
set userInfo(Map<String,String> value) =>
value.forEach((String key, String value) => this._store[key] = value);
}
class _LocalProviderStorage {
Storage get _lcl => window.localStorage;
final Map<String,String> _mem = <String,String>{};
String _get(String key) => key?.isEmpty ?? true ? '' : this._mem[key] ?? (this._lcl[key] ?? '');
void _set(String key, dynamic value) {
if (key?.isEmpty ?? true) return;
value = this._map(value);
this._lcl[key] = value;
this._mem[key] = value;
}
String _map(dynamic value) => value is String ? value : value?.toString() ?? '';
_LocalProviderStorage();
String operator [](String key) => _get(key);
void operator []=(String key, dynamic value) => _set(key, value);
}
void main() {
Repository.token = '<sample>';
print(Repository.token);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment