database + tables creation
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
FROM node:20-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
|
||||
RUN npm install
|
||||
RUN npm install dotenv
|
||||
RUN npm install pg
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 3001
|
||||
|
||||
ENV NODE_ENV=development
|
||||
|
||||
CMD ["node", "index.js"]
|
||||
@@ -0,0 +1,76 @@
|
||||
require('dotenv').config();
|
||||
const { Pool } = require('pg');
|
||||
|
||||
const pool = new Pool
|
||||
({
|
||||
user: process.env.POSTGRES_USER,
|
||||
host: process.env.POSTGRES_HOST,
|
||||
database: process.env.POSTGRES_DB,
|
||||
password: process.env.POSTGRES_PASSWORD,
|
||||
port: 5432,
|
||||
});
|
||||
|
||||
async function waitForDb(retries = 10, delay = 2000)
|
||||
{
|
||||
for (let i = 0; i < retries; i++)
|
||||
{
|
||||
try
|
||||
{
|
||||
await pool.query('SELECT 1');
|
||||
console.log('Database is ready!');
|
||||
return ;
|
||||
}
|
||||
catch (err)
|
||||
{
|
||||
await new Promise(r => setTimeout(r, delay));
|
||||
}
|
||||
}
|
||||
throw new Error('Could not connect to database after multiple attempts');
|
||||
}
|
||||
|
||||
async function createTables()
|
||||
{
|
||||
try
|
||||
{
|
||||
await pool.query(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id SERIAL PRIMARY KEY,
|
||||
username VARCHAR(50) UNIQUE NOT NULL,
|
||||
email VARCHAR(100),
|
||||
created_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS messages(
|
||||
id SERIAL PRIMARY KEY,
|
||||
sender_id INT REFERENCES users(id),
|
||||
received_id INT REFERENCES users(id),
|
||||
content TEXT,
|
||||
created_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
`);
|
||||
console.log('Tables created!');
|
||||
}
|
||||
catch (err)
|
||||
{
|
||||
console.error('Error creating tables:', err);
|
||||
}
|
||||
}
|
||||
|
||||
const express = require('express');
|
||||
const app = express();
|
||||
|
||||
async function startServer()
|
||||
{
|
||||
await waitForDb();
|
||||
|
||||
await createTables();
|
||||
|
||||
app.get('/', (req, res) => res.send('Backend running'));
|
||||
|
||||
app.listen(3001, () =>
|
||||
{
|
||||
console.log('Server ready and listening');
|
||||
});
|
||||
}
|
||||
|
||||
startServer();
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"dependencies":
|
||||
{
|
||||
"express": "^4.18.2"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user