-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
105 lines (86 loc) · 2.67 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// cargamos los módulos de electron que vamos a usar
const { app, BrowserWindow, ipcMain } = require('electron');
// cargamos la función para crear un servidor HTTP
const { createServer } = require('http');
// cargamos Next.js
const next = require('next');
// verificamos si estamos en modo desarrollo
const dev = process.env.NODE_ENV !== 'production';
// crearmos nuestra app de Next.js
const nextApp = next({ dev });
// obtenermos la función para manejar peticiones a Next.js
const handler = nextApp.getRequestHandler();
// en esta variable vamos a guardar la instancia de nuestra UI
let win;
function createWindow() {
// iniciamos la app de Next.js
nextApp
.prepare()
.then(() => {
// una vez lista creamos un servidor HTTP que use nuestro
// handler para rutas todas las peticiones HTTP
// que reciba Next.js
const server = createServer((req, res) => {
// si recibimos una petición por fuera de Electron
// respondemos con un 404
if (req.headers['user-agent'].indexOf('Electron') === -1) {
res.writeHead(404);
res.end();
return;
}
res.setHeader('Access-Control-Request-Method', 'GET');
// solo permitimos peticiones GET
if (req.method !== 'GET') {
res.writeHead(405);
res.end('Method Not Allowed');
return;
}
// dejamos que Next maneje las peticiones
return handler(req, res);
});
// empezamos a escuchar el puerto 3000 con el servidor HTTP
server.listen(3000, (error) => {
if (error) throw error;
// una vez iniciamos el servidor creamos una nueva ventana
win = new BrowserWindow({
height: 768,
width: 1366,
webPreferences: {
nodeIntegration: true
}
});
// y abrimos la URL local del servidor HTTP que creamos
win.loadURL('http://localhost:3000');
// abrimos las herramientas de desarrollo
if (dev) {
win.webContents.openDevTools();
}
win.on('close', () => {
// cuando el usuario cierra la ventana borramo `win`
// y paramos el servidor HTTP
win = null;
server.close();
});
});
});
}
// una vez la app esté lista iniciamos una ventana nueva
app.on('ready', createWindow)
// si todas las ventanas se cerraros matamos la aplicación
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
})
// cuando se activa la app volvemos a abrir una ventana nueva
// (algo solo para Mac)
app.on('activate', () => {
if (win === null) {
createWindow();
}
});
// acá vamos a usar el módulo `ipcMain` para recibir mensajes desde
// nuestro proceso de UI y reenviar ese mensaje a quién lo envió
ipcMain.on('message', (event, message) => {
event.sender.send('message', message);
});