Skip to content

Commit

Permalink
refactor and allow dev environment
Browse files Browse the repository at this point in the history
  • Loading branch information
petertimwalker committed Aug 24, 2024
1 parent 38ba45e commit 34e2dcb
Showing 1 changed file with 35 additions and 25 deletions.
60 changes: 35 additions & 25 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,62 +4,72 @@ const dotenv = require('dotenv');
dotenv.config();
const booksRouter = require('./books');
const cors = require('cors');
const isProduction = process.env.NODE_ENV === 'production';
const API_KEY = process.env.API_KEY || 'API_KEY not defined';
const PORT = isProduction ? 443 : 3001;
const allowedOrigins = ['https://peterwalker.xyz'];

app.use(cors({
origin: (origin, callback) => {
if (!origin) {
return callback(new Error('Origin not specified'), false);
}
if (!allowedOrigins.includes(origin)) {
return callback(new Error('Not allowed by CORS'), false);
}
return callback(null, true);
}
}));
if (isProduction) {
app.use(
cors({
origin: (origin, callback) => {
if (!origin) {
return callback(new Error('Origin not specified'), false);
}
if (!allowedOrigins.includes(origin)) {
return callback(new Error('Not allowed by CORS'), false);
}
return callback(null, true);
},
}),
);
createHTTPSServer();
} else {
app.use(cors());
createHTTPServer();
}

app.use((req, res, next) => {
const origin = req.headers.origin;
console.log(`Request origin: ${origin}`);
next();
});

const isProduction = process.env.NODE_ENV === 'production';
const PORT = isProduction ? 443 : 3001;

// Store your API key securely in an environment variable
const API_KEY = process.env.API_KEY || 'API_KEY not defined';

// Route for the root URL '/'
app.get('/', (req, res) => {
res.send('Hi from api.peterwalker.xyz');
});

// Route for '/api/key'
app.get('/api/key', (req, res) => {
console.log('API key requested');
res.json({ apiKey: API_KEY });
});

app.use('/api/books', booksRouter);

if (isProduction) {
function createHTTPServer() {
const http = require('http');

http.createServer(app).listen(PORT, () => {
console.log(`HTTP Server is running on port ${PORT}`);
});
}

function createHTTPSServer() {
const https = require('https');
const fs = require('fs');

const options = {
key: fs.readFileSync(
'/etc/letsencrypt/live/api.peterwalker.xyz/privkey.pem',
),
cert: fs.readFileSync('/etc/letsencrypt/live/api.peterwalker.xyz/fullchain.pem'),
cert: fs.readFileSync(
'/etc/letsencrypt/live/api.peterwalker.xyz/fullchain.pem',
),
};

https.createServer(options, app).listen(PORT, () => {
console.log(`HTTPS Server is running on port ${PORT}`);
});
} else {
const http = require('http');

http.createServer(app).listen(PORT, () => {
console.log(`HTTP Server is running on port ${PORT}`);
});
}

0 comments on commit 34e2dcb

Please sign in to comment.