Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adiciona watermelon Db no front-end #4

Merged
merged 22 commits into from
Sep 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
a6ed060
feat: edit user offiline
ubrando Aug 29, 2024
e33c02a
feat: editar de idoso offline
marcellaanderle Aug 31, 2024
262132e
feat: update component state with new types and default values
Natyrodrigues Aug 31, 2024
1219607
refactor: replace getIdUsuario with useEffect and add error handling
Natyrodrigues Aug 31, 2024
9a64fa0
refactor: move handleErrors function and add salvarNoBancoLocal function
Natyrodrigues Aug 31, 2024
9649dc8
refactor: move salvar
Natyrodrigues Aug 31, 2024
7e10395
refactor: replace postIdoso with salvarNoBancoLocal and switch to Toa…
Natyrodrigues Aug 31, 2024
699b532
feat: update component state with new types and default values
Natyrodrigues Aug 31, 2024
07006c2
refactor: replace getIdUsuario with useEffect and add error handling
Natyrodrigues Aug 31, 2024
d6e5f69
refactor: move handleErrors function and add salvarNoBancoLocal function
Natyrodrigues Aug 31, 2024
c763598
refactor: move salvar
Natyrodrigues Aug 31, 2024
9977458
refactor: replace postIdoso with salvarNoBancoLocal and switch to Toa…
Natyrodrigues Aug 31, 2024
49fb7ec
refactor: remove unused metricas array
Natyrodrigues Aug 31, 2024
93ca625
refactor: remove body object and related logic
Natyrodrigues Aug 31, 2024
2da047e
refactor: remove unused cadastrarMetricas function
Natyrodrigues Aug 31, 2024
8c36f24
feat: add imports for database, models, and utilities
Natyrodrigues Aug 31, 2024
178cee5
feat: implementação do schema do banco
GabrielSMonteiro Aug 31, 2024
f664374
style: fix indentation and spacing
Natyrodrigues Aug 31, 2024
e304811
feat: cadastro de idoso offline
Natyrodrigues Aug 31, 2024
882d6fe
Merge remote-tracking branch 'origin/feat/offiline-front' into feat/o…
Natyrodrigues Aug 31, 2024
9026ba3
Merge remote-tracking branch 'origin/feat/offiline-front' into feat/o…
marcellaanderle Aug 31, 2024
15a851b
feat: listar de idosos offline
sebazac332 Aug 31, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions src/app/db/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import SQLiteAdapter from '@nozbe/watermelondb/adapters/sqlite'
import schema from './schema'
import migrations from './migrations'
import User from '../model/User'
import Idoso from '../model/Idoso'
// import Post from './model/Post' // ⬅️ You'll import your Models here

// First, create the adapter to the underlying database:
const adapter = new SQLiteAdapter({
schema,
// (You might want to comment it out for development purposes -- see Migrations documentation)
migrations,
// (optional database name or file system path)
// dbName: 'myapp',
// (recommended option, should work flawlessly out of the box on iOS. On Android,
Expand All @@ -28,7 +28,7 @@ const database = new Database({
adapter,
modelClasses: [
// Post, // ⬅️ You'll add Models to Watermelon here
User
User, Idoso
],
});

Expand Down
36 changes: 33 additions & 3 deletions src/app/db/migrations.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,37 @@
import { schemaMigrations } from '@nozbe/watermelondb/Schema/migrations'
import { schemaMigrations } from '@nozbe/watermelondb/Schema/migrations';
import { tableSchema } from '@nozbe/watermelondb';

// Define a migração para a versão 2 do banco de dados
export default schemaMigrations({
migrations: [
// We'll add migration definitions here later
{
toVersion: 2,
steps: [
// Passo para adicionar as colunas à tabela 'users' se elas ainda não existirem
{
type: 'add_columns',
table: 'users',
columns: [
{ name: 'created_at', type: 'number' },
{ name: 'updated_at', type: 'number' },
],
},
// Passo para criar a tabela 'idoso' se ela ainda não existir
{
type: 'create_table',
schema: tableSchema({
name: 'idoso',
columns: [
{ name: 'nome', type: 'string' },
{ name: 'dataNascimento', type: 'string' },
{ name: 'tipoSanguineo', type: 'string' },
{ name: 'telefoneResponsavel', type: 'string' },
{ name: 'descricao', type: 'string', isOptional: true },
{ name: 'user_id', type: 'string', isIndexed: true },
],
}),
},
],
},
],
})
});
53 changes: 34 additions & 19 deletions src/app/db/schema.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,36 @@
import { appSchema, tableSchema } from '@nozbe/watermelondb'
import { appSchema, tableSchema } from '@nozbe/watermelondb';


export default appSchema({
version: 1,
tables: [
// We'll add tableSchemas here later
tableSchema({
name: 'users',
columns: [
{ name: 'external_id', type: 'string' },
{ name: 'name', type: 'string' },
{ name: 'email', type: 'string' },
{ name: 'photo', type: 'string' },
{ name: 'admin', type: 'boolean'},
{ name: 'password', type: 'string' },
{ name: 'created_at', type: 'number' },
{ name: 'updated_at', type: 'number' }
]
})
]
})
version: 5,
tables: [
tableSchema({
name: 'users',
columns: [
{ name: 'external_id', type: 'string' },
{ name: 'name', type: 'string' },
{ name: 'email', type: 'string' },
{ name: 'photo', type: 'string' },
{ name: 'admin', type: 'boolean' },
{ name: 'photo', type: 'string' },
{ name: 'password', type: 'string' },
{ name: 'created_at', type: 'number' },
{ name: 'updated_at', type: 'number' },
],
}),
tableSchema({
name: 'idoso',
columns: [
{ name: 'nome', type: 'string' },
{ name: 'dataNascimento', type: 'string' },
{ name: 'tipoSanguineo', type: 'string' },
{ name: 'telefoneResponsavel', type: 'string' },
{ name: 'descricao', type: 'string' },
{ name: 'foto', type: 'string' },
{ name: 'user_id', type: 'string', isIndexed: true },
{ name: 'created_at', type: 'number' },
{ name: 'updated_at', type: 'number' },
],
}),
],
});
20 changes: 20 additions & 0 deletions src/app/model/Idoso.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Model } from '@nozbe/watermelondb';
import { text, field, readonly, relation, date } from '@nozbe/watermelondb/decorators';
import User from './User';

export default class Idoso extends Model {
static table = 'idoso';

@text('nome') nome!: string;
@text('dataNascimento') dataNascimento!: string;
@field('tipoSanguineo') tipoSanguineo!: string;
@text('telefoneResponsavel') telefoneResponsavel!: string;
@text('descricao') descricao!: string;

@field('user_id') userId!: string;

@relation('users', 'user_id') user!: User;

@readonly @date('created_at') createdAt!: Date;
@readonly @date('updated_at') updatedAt!: Date;
}
9 changes: 5 additions & 4 deletions src/app/model/User.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
// model/Post.js
import { Model } from '@nozbe/watermelondb';
import { text, field, date, readonly } from '@nozbe/watermelondb/decorators';
import { text, field, date, readonly, children } from '@nozbe/watermelondb/decorators';
import Idoso from './Idoso';

export default class User extends Model {
static table = 'users';

// ID coming from the API
@text('external_id') externalId!: string;
@text('name') name!: string;
@text('email') email!: string;
Expand All @@ -14,4 +13,6 @@ export default class User extends Model {
@text('password') password!: string;
@readonly @date('created_at') createdAt!: Date;
@readonly @date('updated_at') updatedAt!: Date;
}

@children('idoso') idosos!: Idoso[];
}
100 changes: 100 additions & 0 deletions src/app/private/pages/CadastroIdosoExemplo.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import AsyncStorage from "@react-native-async-storage/async-storage";
import React, { useEffect, useState } from "react";
import { Image, StyleSheet, Text, View, Button, ToastAndroid } from "react-native";
import { ScrollView } from "react-native";
import database from "../../db";
import Idoso from "../../model/Idoso";
import { ETipoSanguineo } from "../../interfaces/idoso.interface";
import { Collection } from "@nozbe/watermelondb";
import { useRouter } from "expo-router";
import { IUser } from "../../interfaces/user.interface";


export default function InsertIdoso() {
const [idUsuario, setIdUsuario] = useState<number | null>(null);
const router = useRouter();

useEffect(() => {
const getIdUsuario = async () => {
try {
const response = await AsyncStorage.getItem("usuario");
if (response) {
const usuario = JSON.parse(response) as IUser;
setIdUsuario(usuario.id);
console.log("Usuário logado:", usuario);
} else {
console.log("Usuário não encontrado no AsyncStorage.");
}
} catch (error) {
console.error("Erro ao obter usuário:", error);
}
};

getIdUsuario();
}, []);

const handleInsertIdoso = async () => {
if (!idUsuario) {
ToastAndroid.show("Usuário não encontrado.", ToastAndroid.SHORT);
return;
}

try {
await database.write(async () => {
const idosoCollection = database.get('idoso') as Collection<Idoso>;

await idosoCollection.create((idoso) => {
idoso.nome = 'João da Silva';
idoso.dataNascimento = new Date('1945-07-15').toISOString();
idoso.telefoneResponsavel = '987654321';
idoso.descricao = 'Idoso exemplo para testes.';
idoso.tipoSanguineo = ETipoSanguineo.O_POSITIVO;
idoso.userId = idUsuario.toString();
});
});

ToastAndroid.show("Idoso inserido com sucesso!", ToastAndroid.SHORT);
router.push("/private/pages/listarIdosos");
} catch (error) {
console.error("Erro ao inserir o idoso:", error);
ToastAndroid.show("Erro ao inserir o idoso.", ToastAndroid.SHORT);
}
};

return (
<View style={styles.container}>
<ScrollView contentContainerStyle={styles.scrollViewContent}>
<View style={styles.imagem}>
<Image
source={require("../../../../assets/logo2.png")}
style={{ width: 280, height: 90 }}
/>
</View>
<Text style={styles.titulo}>Inserir Idoso de Exemplo</Text>
<Button title="Salvar Idoso Exemplo" onPress={handleInsertIdoso} color="#2CCDB5" />
</ScrollView>
</View>
);
}

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
scrollViewContent: {
flexGrow: 1,
justifyContent: "center",
alignItems: "center",
},
imagem: {
marginBottom: 20,
},
titulo: {
fontSize: 28,
fontWeight: "300",
textAlign: "center",
marginBottom: 20,
},
});
Loading
Loading