Created
August 8, 2021 21:28
-
-
Save guilhermecarvalhocarneiro/9cbb841b18d5d0ca9217a7cb6049b338 to your computer and use it in GitHub Desktop.
Classe para persistência de dados local utilizando o Sembast
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Local Data do model Paciente | |
/// | |
/// Os Métodos padrões gerados são: | |
/// fecthAll() -> Recupera a lista de Paciente. | |
/// save() -> Salva os dados de uma instância do Paciente. | |
/// detail() -> Recupera os detalhes de Paciente. | |
/// update() -> Atualiza os dados de uma instância do Paciente. | |
/// 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:flutter/foundation.dart'; | |
import 'package:sembast/sembast_io.dart' as smbt_io; | |
import 'package:sembast/sembast.dart' as smbt; | |
import 'package:path_provider/path_provider.dart'; | |
import 'model.dart'; | |
import '../../../utils/config.dart'; | |
import '../../../utils/exception.dart'; | |
class PacienteData { | |
PacienteModel _pacienteModel = PacienteModel(nome: ""); | |
static final PacienteData _instance = PacienteData.internal(); | |
factory PacienteData() => _instance; | |
PacienteData.internal(); | |
late smbt.Database _db; | |
final String _storeName = "PacienteStoreDB"; | |
/// Método para inicialiar o banco de dados criando a tabela. | |
Future<smbt.Database?> initDb() async { | |
try { | |
var dir = await getApplicationDocumentsDirectory(); | |
await dir.create(recursive: true); | |
var dbPath = join(dir.path, 'oralx.db'); | |
return await smbt_io.databaseFactoryIo.openDatabase(dbPath); | |
} catch (error, exception) { | |
ExceptionCustom.data( | |
"Ocorreu no método initDb do PacienteData", | |
"Error: ${error.toString()}\nException: ${exception.toString()}", | |
); | |
} | |
return null; | |
} | |
/// Método para recuperar todos os dados de Paciente | |
/// | |
/// returns: | |
/// Instância do PacienteModel | |
Future<List<PacienteModel>?> fetchAll() async { | |
try { | |
_db = (await initDb())!; | |
var _store = smbt.intMapStoreFactory.store(_storeName); | |
var _data = await _store.find(_db); | |
return _data.map((snapshot) { | |
return PacienteModel.fromMap(snapshot.value); | |
}).toList(); | |
} catch (error, exception) { | |
ExceptionCustom.data( | |
"Ocorreu no método fetchAll do PacienteData", | |
"Error: ${error.toString()}\nException: ${exception.toString()}", | |
); | |
return null; | |
} finally { | |
_db.close(); | |
} | |
} | |
/// Método para recuperar o primeiro registro de Paciente | |
/// | |
/// returns: | |
/// Instância do PacienteModel | |
Future<PacienteModel?> get(int id) async { | |
try { | |
_db = (await initDb())!; | |
var _store = smbt.intMapStoreFactory.store(_storeName); | |
var _data = await _store.findFirst(_db); | |
return PacienteModel.fromMap(_data.value); | |
} catch (error, exception) { | |
ExceptionCustom.data( | |
"Ocorreu no método get do PacienteData", | |
"Error: ${error.toString()}\nException: ${exception.toString()}", | |
); | |
return null; | |
} finally { | |
_db.close(); | |
} | |
} | |
/// Método para salvar localmente um(a) Paciente | |
/// | |
/// returns: | |
/// bool -> true salvo com sucesso, false ocorreu um erro | |
Future<bool> save(PacienteModel paciente) async { | |
try { | |
_db = (await initDb())!; | |
var _store = smbt.intMapStoreFactory.store(_storeName); | |
// Salvando o dado do novo paciente | |
await _store.add(_db, paciente.toMap()); | |
return true; | |
} catch (error, exception) { | |
ExceptionCustom.data( | |
"Ocorreu no método save do PacienteData", | |
"Error: ${error.toString()}\nException: ${exception.toString()}", | |
); | |
return false; | |
} finally { | |
_db.close(); | |
} | |
} | |
/// Método para deletar todos os registros do(a) Paciente | |
/// | |
/// returns: | |
/// bool -> true salvo com sucesso, false ocorreu um erro | |
Future<bool> deleteAll() async { | |
try { | |
_db = (await initDb())!; | |
var _store = smbt.intMapStoreFactory.store(_storeName); | |
// Apagando todos os registros anteriores | |
await _store.delete(_db); | |
return true; | |
} catch (error, exception) { | |
ExceptionCustom.data( | |
"Ocorreu no método deletar do PacienteData", | |
"Error: ${error.toString()}\nException: ${exception.toString()}", | |
); | |
return false; | |
} finally { | |
_db.close(); | |
} | |
} | |
/// Método para deletar um registro do(a) Paciente | |
/// | |
/// returns: | |
/// bool -> true salvo com sucesso, false ocorreu um erro | |
Future<bool> delete(int id) async { | |
try { | |
_db = (await initDb())!; | |
var _store = smbt.intMapStoreFactory.store(_storeName); | |
await _store.delete(_db); | |
return true; | |
} catch (error, exception) { | |
ExceptionCustom.data( | |
"Ocorreu no método deletar do PacienteData", | |
"Error: ${error.toString()}\nException: ${exception.toString()}", | |
); | |
return false; | |
} finally { | |
_db.close(); | |
} | |
} | |
/// Método para atualizar um registro do(a) Paciente | |
/// | |
/// returns: | |
/// bool -> true salvo com sucesso, false ocorreu um erro | |
Future<bool> update(PacienteModel paciente) async { | |
try { | |
_db = (await initDb())!; | |
var _store = smbt.intMapStoreFactory.store(_storeName); | |
final finder = smbt.Finder(filter: smbt.Filter.byKey(paciente.id)); | |
await _store.update( | |
_db, | |
paciente.toMap(), | |
finder: finder, | |
); | |
return true; | |
} catch (error, exception) { | |
ExceptionCustom.data( | |
"Ocorreu no método update do PacienteData", | |
"Error: ${error.toString()}\nException: ${exception.toString()}", | |
); | |
return false; | |
} finally { | |
_db.close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment