Skip to content

Instantly share code, notes, and snippets.

@guilhermecarvalhocarneiro
Created May 13, 2021 12:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guilhermecarvalhocarneiro/d16011c77dff4278e28b9eb4d9cb60ff to your computer and use it in GitHub Desktop.
Save guilhermecarvalhocarneiro/d16011c77dff4278e28b9eb4d9cb60ff to your computer and use it in GitHub Desktop.
/// Local Data do model Auth
///
/// Os Métodos padrões gerados são:
/// fecthAll() -> Recupera a lista de Auth.
/// save() -> Salva os dados de uma instância do Auth.
/// detail() -> Recupera os detalhes de Auth.
/// update() -> Atualiza os dados de uma instância do Auth.
/// delete() -> Deleta um registro.
/// deleteAll() -> Deleta todos os registros.
/// [Travar o arquivo]
/// Caso deseje "travar" o arquivo para não ser parseado novamente
/// pelo manage do Django adicione um # antes da palavra abaixo
/// FileLocked
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sembast/sembast.dart' as smbt;
import 'package:sembast/sembast_io.dart' as smbt_io;
import '../../utils/config.dart';
import 'model.dart';
class AuthData {
final AuthModel _authModel = AuthModel();
static final AuthData _instance = AuthData.internal();
factory AuthData() => _instance;
AuthData.internal();
smbt.Database _db;
final String _storeName = "AuthStoreDB";
Future<smbt.Database> initDb() async {
try {
// get the application documents directory
final dir = await getApplicationDocumentsDirectory();
// make sure it exists
await dir.create(recursive: true);
// build the database path
final dbPath = join(dir.path, 'oralx.db');
// open the database
return await smbt_io.databaseFactoryIo.openDatabase(dbPath);
} catch (error, exception) {
DebugPrint.error("DebugErro: no método initDB do AuthData -> $error | $exception");
}
return null;
}
Future<List<AuthModel>> fetchAll() async {
try {
_db = await initDb();
final _store = smbt.intMapStoreFactory.store(_storeName);
final _data = await _store.find(_db);
return _data.map((snapshot) => AuthModel.fromMap(snapshot.value)).toList();
} catch (error, exception) {
DebugPrint.error("DebugErro: no método fetchAll do AuthData -> $error | $exception");
return null;
} finally {
_db?.close();
}
}
Future<AuthModel> get(int id) async {
try {
_db = await initDb();
final _store = smbt.intMapStoreFactory.store(_storeName);
if (_store != null) {
// TODO Verificar o erro
final _data = await _store.findFirst(_db);
if (_data != null) {
return AuthModel.fromMap(_data.value);
}
}
return null;
} catch (error, exception) {
DebugPrint.error("DebugErro: no método get do AuthData -> $error | $exception");
return null;
} finally {
_db?.close();
}
}
Future<bool> save(AuthModel auth) async {
try {
await deleteAll();
_db = await initDb();
final _store = smbt.intMapStoreFactory.store(_storeName);
await _store.add(_db, auth.toMap());
return true;
} catch (error, exception) {
DebugPrint.error("DebugErro: no método save do AuthData -> $error | $exception");
return false;
} finally {
_db?.close();
}
}
/// Método para salvar os dados do usuário logado localmente
Future<bool> saveSignInData(AuthModel auth) async {
try {
_db = await initDb();
final _store = smbt.intMapStoreFactory.store(_storeName);
await _store.add(_db, auth.toMap());
return true;
} catch (error) {
return false;
} finally {
_db?.close();
}
}
Future<bool> deleteAll() async {
try {
_db = await initDb();
final _store = smbt.intMapStoreFactory.store(_storeName);
await _store.delete(_db);
return true;
} catch (error, exception) {
DebugPrint.error("DebugErro: no método deleteAll do AuthData -> $error | $exception");
return false;
} finally {
_db?.close();
}
}
Future<bool> delete(int id) async {
try {
_db = await initDb();
final _store = smbt.intMapStoreFactory.store(_storeName);
await _store.delete(_db);
return true;
} catch (error, exception) {
DebugPrint.error("DebugErro: no método delete do AuthData -> $error | $exception");
return false;
} finally {
_db?.close();
}
}
Future<bool> update(AuthModel auth) async {
try {
_db = await initDb();
final _store = smbt.intMapStoreFactory.store(_storeName);
return true;
} catch (error, exception) {
DebugPrint.error("DebugErro: No método save do AuthData -> $error | $exception");
return false;
} finally {
_db?.close();
}
}
/// Método para consultar o Token JWT
Future<String> getJWTToken() async {
try {
final _data = await get(0);
if (_data != null) {
final String token = _data?.token ?? "";
if (token.isNotEmpty) {
return token;
}
}
return null;
} catch (e) {
DebugPrint.error("DebugError: Erro $e ao executar o getJWTToken do AuthData");
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment