Skip to content

Commit

Permalink
refactor(main/index.js): modularizando arquivo;
Browse files Browse the repository at this point in the history
dividindo arquivo index.js em 2 arquivos com funções especializadas para cada arquivo, sendo window.js para configurações de janela e ipcHandlers para procedimentos ipc.
  • Loading branch information
GustavoOly committed Oct 15, 2024
1 parent b373b88 commit 37498ba
Show file tree
Hide file tree
Showing 3 changed files with 126 additions and 91 deletions.
96 changes: 5 additions & 91 deletions src/main/index.js
Original file line number Diff line number Diff line change
@@ -1,48 +1,7 @@
import { app, shell, BrowserWindow, ipcMain } from 'electron';
import { autoUpdater } from 'electron-updater';
import { join } from 'path';
import { electronApp, optimizer, is } from '@electron-toolkit/utils';
import icon from '../../resources/logo-ipameri-min.png?asset';
import db from '../../database/database.js';

function createWindow() {
const mainWindow = new BrowserWindow({
width: 1200,
height: 800,
minHeight: 600,
minWidth: 900,
show: false,
autoHideMenuBar: true,
frame: true,
...(process.platform === 'linux' || process.platform === 'win32' ? { icon } : {}),
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
sandbox: false,
contextIsolation: true,
enableRemoteModule: false,
nodeIntegration: false,
}
});

mainWindow.on('ready-to-show', () => {
mainWindow.show();
});

mainWindow.webContents.setWindowOpenHandler((details) => {
shell.openExternal(details.url);
return { action: 'deny' };
});

if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL']);
} else {
mainWindow.loadFile(join(__dirname, '../renderer/index.html'));
}

autoUpdater.on('update-downloaded', () => {
autoUpdater.quitAndInstall();
})
}
import { app, BrowserWindow } from 'electron';
import { electronApp, optimizer } from '@electron-toolkit/utils';
import { createWindow } from './window';
import { setupIpcHandlers } from './ipcHandlers';

app.whenReady().then(() => {
electronApp.setAppUserModelId('com.electron');
Expand All @@ -51,52 +10,7 @@ app.whenReady().then(() => {
optimizer.watchWindowShortcuts(window);
});

ipcMain.handle('get-emprestimos', async () => {
const stmt = db.prepare('SELECT * FROM emprestimos');
const items = stmt.all();
console.log('Emprestimos carregados:', items);
return items;
});

ipcMain.handle('update-emprestimo', (event, item) => {
const stmt = db.prepare('UPDATE emprestimos SET nome = ?, telefone = ?, livros = ?, dataEmprestimo = ?, dataDevolucao = ? WHERE id = ?');
const info = stmt.run(item.nome, item.telefone, item.livros, item.dataEmprestimo, item.dataDevolucao, item.id);
console.log('Emprestimo atualizado:', item);
return { changes: info.changes };
});

ipcMain.handle('update-estado-emprestimo', (event, item) => {
console.log('Atualizando item:', item);
const stmt = db.prepare('UPDATE emprestimos SET estado = ? WHERE id = ?');
const info = stmt.run(item.estado, item.id);
console.log('Mudanças feitas:', info.changes);
return { changes: info.changes };
});


ipcMain.handle('delete-emprestimo', (event, id) => {
event.sender.send('delete-emprestimo', id);
const stmt = db.prepare('DELETE FROM emprestimos WHERE id = ?');
const info = stmt.run(id);
console.log('Emprestimo deletado:', id);
return { changes: info.changes };
});

ipcMain.handle('add-emprestimo', (event, item) => {
event.preventDefault();
const currentDate = new Date();
const returnDate = new Date(item.dataDevolucao);
let estado = 'Em andamento';

if (currentDate > returnDate) {
estado = 'Atrasado';
} else if (currentDate.toDateString() === returnDate.toDateString()) {
estado = 'Em andamento';
}
const stmt = db.prepare('INSERT INTO emprestimos (nome, telefone, livros, dataEmprestimo, dataDevolucao, estado) VALUES (?, ?, ?, ?, ?, ?)');
const info = stmt.run(item.nome, item.telefone, item.livros, item.dataEmprestimo, item.dataDevolucao, estado);
return { id: info.lastInsertRowid };
});
setupIpcHandlers();

createWindow();

Expand Down
73 changes: 73 additions & 0 deletions src/main/ipcHandlers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { ipcMain } from 'electron';
import db from '../../database/database.js';

export function setupIpcHandlers() {
ipcMain.handle('get-emprestimos', async () => {
try {
const stmt = db.prepare('SELECT * FROM emprestimos');
const items = stmt.all();
console.log('Emprestimos carregados:', items);
return items;
} catch (error) {
console.error('Erro ao carregar emprestimos:', error);
throw error;
}
});

ipcMain.handle('update-emprestimo', async (_, item) => {
try {
const stmt = db.prepare('UPDATE emprestimos SET nome = ?, telefone = ?, livros = ?, dataEmprestimo = ?, dataDevolucao = ? WHERE id = ?');
const info = stmt.run(item.nome, item.telefone, item.livros, item.dataEmprestimo, item.dataDevolucao, item.id);
console.log('Emprestimo atualizado:', item);
return { changes: info.changes };
} catch (error) {
console.error('Erro ao atualizar emprestimo:', error);
throw error;
}
});

ipcMain.handle('update-estado-emprestimo', async (_, item) => {
try {
console.log('Atualizando item:', item);
const stmt = db.prepare('UPDATE emprestimos SET estado = ? WHERE id = ?');
const info = stmt.run(item.estado, item.id);
console.log('Mudanças feitas:', info.changes);
return { changes: info.changes };
} catch (error) {
console.error('Erro ao atualizar estado do emprestimo:', error);
throw error;
}
});

ipcMain.handle('delete-emprestimo', async (_, id) => {
try {
const stmt = db.prepare('DELETE FROM emprestimos WHERE id = ?');
const info = stmt.run(id);
console.log('Emprestimo deletado:', id);
return { changes: info.changes };
} catch (error) {
console.error('Erro ao deletar emprestimo:', error);
throw error;
}
});

ipcMain.handle('add-emprestimo', async (_, item) => {
try {
const currentDate = new Date();
const returnDate = new Date(item.dataDevolucao);
let estado = 'Em andamento';

if (currentDate > returnDate) {
estado = 'Atrasado';
} else if (currentDate.toDateString() === returnDate.toDateString()) {
estado = 'Em andamento';
}
const stmt = db.prepare('INSERT INTO emprestimos (nome, telefone, livros, dataEmprestimo, dataDevolucao, estado) VALUES (?, ?, ?, ?, ?, ?)');
const info = stmt.run(item.nome, item.telefone, item.livros, item.dataEmprestimo, item.dataDevolucao, estado);
return { id: info.lastInsertRowid };
} catch (error) {
console.error('Erro ao adicionar emprestimo:', error);
throw error;
}
});
}
48 changes: 48 additions & 0 deletions src/main/window.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { BrowserWindow, shell } from 'electron';
import { join } from 'path';
import { autoUpdater } from 'electron-updater';
import { is } from '@electron-toolkit/utils';
import icon from '../../resources/logo-ipameri-min.png?asset';

const WINDOW_OPTIONS = {
width: 1200,
height: 800,
minHeight: 600,
minWidth: 900,
show: false,
autoHideMenuBar: true,
frame: true,
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
sandbox: false,
contextIsolation: true,
enableRemoteModule: false,
nodeIntegration: false,
}
};

export function createWindow() {
const mainWindow = new BrowserWindow({
...WINDOW_OPTIONS,
...(process.platform === 'linux' || process.platform === "win32" ? { icon } : {}),
});

mainWindow.on('ready-to-show', () => {
mainWindow.show();
});

mainWindow.webContents.setWindowOpenHandler((details) => {
shell.openExternal(details.url);
return { action: 'deny' };
});

if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL']);
} else {
mainWindow.loadFile(join(__dirname, '../renderer/index.html'));
}

autoUpdater.on('update-downloaded', () => {
autoUpdater.quitAndInstall();
});
}

0 comments on commit 37498ba

Please sign in to comment.