// server.js const express = require('express'); const bodyParser = require('body-parser'); const routes = require('./routes/routes.js'); const sequelize = require('./db/database.js'); const path = require('path'); const app = express(); const PORT = process.env.PORT || 4000; const relations = require('./db/relations.js'); const sequelizeHooks = require('./db/sequelizeHooks.js'); const { initializeGenres, initializeData } = require('./db/dataInitializer.js'); const killerRouter = require('./routes/killer.routes.js'); // Middleware app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded // CORS Middleware to allow requests from any origin app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header( 'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization' ); if (req.method === 'OPTIONS') { res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET'); return res.status(200).json({}); } next(); }); // ? Routes // * media access route app.use('/api/v1/media/:category/:type', (req, res, next) => { const category = req.params.category; const type = req.params.type; if (!['entries', 'collections', 'franchises'].includes(category)) { return res.status(404).send('Not Found'); } if (!['backdrops', 'posters', 'others'].includes(type)) { return res.status(404).send('Not Found'); } const options = { fallthrough: false, // ! Important: don't call next middleware if file isn't found }; express.static(path.join(__dirname, '..', `uploads/${category}/${type}`), options)(req, res, next); }); // * other api routes app.use('/api/v1', routes); // ! Error handling middleware const errorHandler = require('./middleware/errorHandler'); app.use(errorHandler); // ! KILLER ROUTE: used to crash the backend app.use('/killer', killerRouter); // Start the server const doUpdate = false; console.log(`Syncing database schema...`); sequelize // .sync({force: true}) // will drop all tables and recreate them. .sync({ alter: doUpdate }) // will attempt to automatically alter tables to fit the model definitions. // .sync() .then((result) => { console.log(`Database schema synced...`); initializeData(); app.listen(PORT, () => { //const Entry = require("./models/Entry.js") console.log(`Backend server running on http://localhost:${PORT}`); }); }) .catch(err => { console.log("____________SEQUELIZE SYNC ERROR____________") console.log(err) });