Skip to content

Commit

Permalink
Merge pull request #10 from WodenWang820118/develop
Browse files Browse the repository at this point in the history
feat: migrate to pnpm
  • Loading branch information
WodenWang820118 authored Sep 13, 2024
2 parents 2758196 + 8ee0a59 commit 4b6939d
Show file tree
Hide file tree
Showing 15 changed files with 90,502 additions and 22,145 deletions.
1 change: 1 addition & 0 deletions forge.config.cjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
module.exports = {
packagerConfig: {
asar: true,
ignore: [/^\/node_modules/, /^\/dist\/(?!nest-backend)/],
extraResource: [
'./dist/ng-tracker',
'./dist/nest-backend/main.js',
Expand Down
19 changes: 0 additions & 19 deletions hooks.cjs

This file was deleted.

86 changes: 63 additions & 23 deletions main-process/backend.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ function startBackend(resourcesPath) {
environmentUtils.getEnvironment(),
resourcesPath
);
fileUtils.logToFile(rootBackendFolderPath, `Starting server`, 'info');
const serverPath = join(rootBackendFolderPath, 'main.js');
const databasePath = join(
rootBackendFolderPath,
Expand Down Expand Up @@ -49,47 +50,86 @@ function startBackend(resourcesPath) {
break;
}

fileUtils.writePath(
join(
pathUtils.getRootBackendFolderPath(
environmentUtils.getEnvironment(),
resourcesPath
),
'env.txt'
),
JSON.stringify(env, null, 2)
fileUtils.logToFile(
rootBackendFolderPath,
`Starting server with environment: ${JSON.stringify(env, null, 2)}`
);

fileUtils.writePath(
join(
pathUtils.getRootBackendFolderPath(
environmentUtils.getEnvironment(),
resourcesPath
),
'serverPath.txt'
),
serverPath
);
fileUtils.logToFile(rootBackendFolderPath, `Server path: ${serverPath}`);

// return utilityProcess.fork(serverPath, { env });
return fork(serverPath, { env });
}

async function checkIfPortIsOpen(urls, maxAttempts = 20, timeout = 2000) {
async function checkIfPortIsOpen(
urls,
maxAttempts = 20,
timeout = 1000,
resourcesPath,
loadingWindow
) {
const logFilePath = join(
pathUtils.getRootBackendFolderPath(
environmentUtils.getEnvironment(),
resourcesPath
)
);
await new Promise((resolve) => setTimeout(resolve, 5000)); // await the backend to start
fileUtils.logToFile(logFilePath, `Checking if port is open`, 'info');
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
for (const url of urls) {
try {
const response = await fetch(url);
if (response) {

console.log('Response status:', response.status);
console.log(
'Response headers:',
JSON.stringify(Object.fromEntries(response.headers), null, 2)
);

const responseData = await response.text();
console.log('Response body:', responseData);

fileUtils.logToFile(logFilePath, responseData, 'info');

if (response.ok) {
console.log('Server is ready');
fileUtils.logToFile(
logFilePath,
`Server is ready: ${responseData}`,
'info'
);
return true; // Port is open
} else {
console.log(`Server responded with status: ${response.status}`);
fileUtils.logToFile(
logFilePath,
`Server responded with status: ${response.status}`,
'warning'
);
}
} catch (error) {
console.log(`Attempt ${attempt}: Waiting for server to start...`);
console.error(`Attempt ${attempt}: Error connecting to ${url}:`, error);
fileUtils.logToFile(
logFilePath,
`Attempt ${attempt}: Error connecting to ${url}: ${error.toString()}`,
'error'
);
fileUtils.logToFile(
logFilePath,
`Attempt ${attempt}: ${error.toString()}`,
'error'
);
}
}
await new Promise((resolve) => setTimeout(resolve, timeout)); // Wait for 2 seconds before retrying

if (attempt < maxAttempts) {
console.log(`Waiting ${timeout}ms before next attempt...`);
await new Promise((resolve) => setTimeout(resolve, timeout));
}
}

loadingWindow.close();
throw new Error(
`Failed to connect to the server after ${maxAttempts} attempts`
);
Expand Down
25 changes: 0 additions & 25 deletions main-process/command-utils.cjs

This file was deleted.

2 changes: 1 addition & 1 deletion main-process/constants.cjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

const URLs = ['http://localhost:5000', 'http://localhost:3000'];
const URLs = ['http://localhost:5000/health', 'http://localhost:3000/health'];
const ROOT_DATABASE_NAME = 'database.sqlite3';

module.exports = {
Expand Down
17 changes: 13 additions & 4 deletions main-process/file-utils.cjs
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
'use strict';
const { writeFileSync } = require('fs');
const { appendFileSync } = require('fs');
const { join } = require('path');

function writePath(filePath, content) {
writeFileSync(filePath, content, 'utf8');
function logToFile(path, message, type = 'info') {
const logPath = join(path, `${type}.log`);
const timestamp = new Date().toISOString();
const logMessage = `${timestamp} - ${type.toUpperCase()}: ${message}\n`;

try {
appendFileSync(logPath, logMessage);
} catch (error) {
console.error('Failed to write to log file:', error);
}
}

module.exports = {
writePath,
logToFile,
};
20 changes: 8 additions & 12 deletions main-process/frontend.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -50,23 +50,19 @@ function createWindow(env, resourcesPath) {

try {
const entryPath = pathUtils.getFrontendPath(env, resourcesPath);
fileUtils.writePath(
join(
pathUtils.getRootBackendFolderPath(env, resourcesPath),
'entryPath.txt'
),
entryPath
fileUtils.logToFile(
join(pathUtils.getRootBackendFolderPath(env, resourcesPath)),
entryPath,
'info'
);
mainWindow.loadFile(entryPath);
mainWindow.webContents.openDevTools(); // Open DevTools in development
} catch (e) {
console.error(e);
fileUtils.writePath(
join(
pathUtils.getRootBackendFolderPath(env, resourcesPath),
'entryPathError.txt'
),
e.message
fileUtils.logToFile(
join(pathUtils.getRootBackendFolderPath(env, resourcesPath)),
e,
'error'
);
}
}
Expand Down
58 changes: 44 additions & 14 deletions main.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,70 +9,100 @@ const constants = require('./main-process/constants.cjs');
const fileUtils = require('./main-process/file-utils.cjs');

let server;
app.commandLine.appendSwitch('disable-gpu');
app.commandLine.appendSwitch('use-gl', 'desktop');

app.whenReady().then(async () => {
server = backend.startBackend(process.resourcesPath);
const loadingWindow = frontend.createLoadingWindow();
server.once('spawn', async () => {
try {
if (await backend.checkIfPortIsOpen(constants.URLs, 20, 2000)) {
if (
await backend.checkIfPortIsOpen(
constants.URLs,
20,
2000,
process.resourcesPath,
loadingWindow
)
) {
loadingWindow.close();
frontend.createWindow(
environmentUtils.getEnvironment(),
process.resourcesPath
);
}
} catch (error) {
console.error(error.message);
fileUtils.writePath(
console.error(error);
fileUtils.logToFile(
join(
pathUtils.getRootBackendFolderPath(
environmentUtils.getEnvironment(),
process.resourcesPath
),
'portErrorLog.txt'
)
),
error.message
error,
'error'
);
}
});

server.on('message', (message) => {
console.log(`Message from child: ${message}`);
fileUtils.logToFile(
join(
pathUtils.getRootBackendFolderPath(
environmentUtils.getEnvironment(),
process.resourcesPath
)
),
message,
'info'
);
});

server.on('error', (error) => {
console.error(`Error from child: ${error}`);
fileUtils.writePath(
fileUtils.logToFile(
join(
pathUtils.getRootBackendFolderPath(
environmentUtils.getEnvironment(),
process.resourcesPath
),
'childErrorLog.txt'
)
),
error
error,
'error'
);
});

server.on('exit', (code, signal) => {
console.log(`Child exited with code ${code} and signal ${signal}`);
fileUtils.writePath(
fileUtils.logToFile(
join(
pathUtils.getRootBackendFolderPath(
environmentUtils.getEnvironment(),
process.resourcesPath
),
'childExitLog.txt'
)
),
`Child exited with code ${code} and signal ${signal}`
`Child exited with code ${code} and signal ${signal}`,
'error'
);
});
});

app.on('before-quit', async () => {
// Perform any necessary cleanup here
console.log('App is about to quit. Performing cleanup...');
fileUtils.logToFile(
join(
pathUtils.getRootBackendFolderPath(
environmentUtils.getEnvironment(),
process.resourcesPath
)
),
'App is about to quit. Performing cleanup...',
'info'
);
if (server) {
server.kill();
}
Expand Down
2 changes: 2 additions & 0 deletions nest-backend/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ import { ConfigModule } from '@nestjs/config';
import { dataBaseConfig } from '../app/database/database.config';
import { SequelizeModule } from '@nestjs/sequelize';
import { TaskModule } from './task/task.module';
import { HealthModule } from './health/health.module';
@Module({
imports: [
HealthModule,
ConfigModule.forRoot(),
SequelizeModule.forRoot(dataBaseConfig),
TaskModule,
Expand Down
12 changes: 12 additions & 0 deletions nest-backend/src/app/health/health.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Controller, Get } from '@nestjs/common';

@Controller('health')
export class HealthController {
@Get()
check() {
return {
status: 'ok',
message: 'Backend is up and running',
};
}
}
7 changes: 7 additions & 0 deletions nest-backend/src/app/health/health.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Module } from '@nestjs/common';
import { HealthController } from './health.controller';

@Module({
controllers: [HealthController],
})
export class HealthModule {}
Loading

0 comments on commit 4b6939d

Please sign in to comment.