Skip to content

Commit

Permalink
Merge pull request #4 from fga-eps-mds/feat/offiline-front
Browse files Browse the repository at this point in the history
Adiciona watermelon Db no front-end
  • Loading branch information
VictorJorgeFGA authored Sep 2, 2024
2 parents b27c66a + 15a851b commit 242b569
Show file tree
Hide file tree
Showing 12 changed files with 1,205 additions and 839 deletions.
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

0 comments on commit 242b569

Please sign in to comment.