Skip to content

Commit

Permalink
removed testing of db
Browse files Browse the repository at this point in the history
  • Loading branch information
LukeRenton committed Apr 30, 2024
1 parent fd93640 commit f7cb7ce
Show file tree
Hide file tree
Showing 4 changed files with 79 additions and 48 deletions.
3 changes: 2 additions & 1 deletion .github/workflows/master_cryptidsgame-app.yml
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,5 @@ jobs:
with:
app-name: 'CryptidsGame-App'
slot-name: 'Production'
package: .
package: .

8 changes: 0 additions & 8 deletions server/__tests__/server.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ const request = require('supertest');
const path = require('path');
const express = require('express');
const boardRoutes = require('../routes/boardRoutes');
const dbRoutes = require('../routes/dbRoutes');

// Import the Express app
const createApp = require('../server');
Expand All @@ -13,7 +12,6 @@ app.use(express.json({ type: '*/*' }));
app.use(express.static(path.join(__dirname, '../../client/build')));

app.use("/map", boardRoutes);
app.use("/db", dbRoutes);

const reactRoutes = ['/'];
app.get(reactRoutes, (req, res) => {
Expand All @@ -33,10 +31,4 @@ describe('Express App Tests', () => {
const response = await request(app).get('/map/random-map?mode=intro&players=4');
expect(response.status).toBe(200);
});

// Test /db route
test('should handle /db/test route', async () => {
const response = await request(app).get('/db/test');
expect(response.status).toBe(200); // expect proper status code
});
});
109 changes: 72 additions & 37 deletions server/routes/dbRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,60 +2,95 @@ const express = require('express');
const router = express.Router();
require('dotenv').config();
const { Client } = require('pg');
const { addUser, validateUserLogin, removeUser } = require('../controllers/dbController');

// Assume client connection is established
const client = new Client({
user: process.env.PG_USER,
host: process.env.PG_HOST,
database: process.env.PG_DATABASE,
password: process.env.PG_PASSWORD,
port: process.env.PG_PORT,
ssl: {
rejectUnauthorized: false,
},
});
const { addUser, validateUserLogin } = require('../controllers/dbController');

// Create PostgreSQL client instance
function createClient() {
return new Client({
user: process.env.PG_USER,
host: process.env.PG_HOST,
database: process.env.PG_DATABASE,
password: process.env.PG_PASSWORD,
port: process.env.PG_PORT,
ssl: {
rejectUnauthorized: false,
},
});
}

client.connect((err) => {
if (err) {
console.error('Failed to connect to PostgreSQL:', err.message);
} else {
console.log('Connected to PostgreSQL');
}
});
let client;

// Connect to PostgreSQL
async function connectClient() {
client = createClient();
try {
await client.connect();
console.log('Connected to PostgreSQL');
} catch (err) {
console.error('Failed to connect to PostgreSQL:', err.message);
throw err;
}
}

(async () => {
try {
await connectClient();
} catch (err) {
console.error("Critical: Can't start server. Exiting.", err.message);
process.exit(1); // Exit if PostgreSQL connection fails
}
})();

// Middleware to ensure client connection is ready before routing
router.use(async (req, res, next) => {
if (!client) {
return res.status(503).json({ error: 'Database connection unavailable' });
}
next(); // If client is available, proceed with the request
});

// Route to add a new user
router.post('/register', async (req, res) => {
const username = req.body.username;
const password = req.body.password;
console.log(req);
console.log(username + ' ' + password);
try {
const newUser = await addUser(client, username, password);
res.status(201).json(newUser); // Return the newly created user
} catch (err) {
res.status(500).json({ error: err.message }); // Return error message if something goes wrong
}
router.post('/register', async (req, res, next) => {
try {
const { username, password } = req.body;
const newUser = await addUser(client, username, password);
res.status(201).json(newUser); // Return the newly created user
} catch (err) {
next(err); // Pass error to error handler middleware
}
});

router.get('/test', async(req, res) => {
// Test route
router.get('/test', (req, res) => {
res.status(200).send("Success");
})
});

// Route to validate user login
router.post('/login', async (req, res) => {
const { username, password } = req.body;
router.post('/login', async (req, res, next) => {
try {
const { username, password } = req.body;
const isValidUser = await validateUserLogin(client, username, password);
if (isValidUser) {
res.status(200).json({ message: 'Login successful' }); // User found
} else {
res.status(401).json({ message: 'Invalid credentials' }); // User not found
}
} catch (err) {
res.status(500).json({ error: err.message }); // Handle error
next(err); // Pass error to error handler middleware
}
});

// Centralized error handler middleware
router.use((err, req, res, next) => {
console.error('Error:', err.message);
res.status(500).json({ error: 'Internal server error' }); // General error response
});

// Clean up PostgreSQL client when the server exits
process.on('exit', () => {
if (client) {
client.end();
}
});

module.exports = router;
module.exports = router;
7 changes: 5 additions & 2 deletions server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const boardRoutes = require('./routes/boardRoutes');
const dbRoutes = require('./routes/dbRoutes');

const app = express();
const port = process.env.PORT || 5000;
Expand All @@ -15,7 +14,11 @@ app.use(express.static(path.join(__dirname, '../client/build')));


app.use("/map", boardRoutes);
app.use("/db", dbRoutes);

if (process.env.NODE_ENV !== 'test') {
const dbRoutes = require('./routes/dbRoutes');
app.use("/db", dbRoutes);
}


// Handle requests to main react page
Expand Down

0 comments on commit f7cb7ce

Please sign in to comment.