//Libraries const express = require('express'); const multer = require('multer'); const mysql = require('mysql2'); const games = require('./model/games'); const developers = require('./model/developers'); const publishers = require('./model/publishers'); const {request, response} = require("express"); const {check, checkSchema, validationResult} = require("express-validator"); const path = require('path'); const cors = require('cors'); //Setup defaults for script const app = express(); app.use(cors()); app.use(express.static('public')); const storage = multer.diskStorage({ //Logic where to upload files destination: function (request, file, callback) { callback(null, 'public/images/') }, //Logic to name the file when uploaded filename: function (request, file, callback) { callback(null, file.originalname + '-' + Date.now() + path.extname(file.originalname)) } }) const upload = multer({ storage: storage, //Validation for file upload fileFilter: (request, file, callback) => { const allowedFileMimeTypes = ["image/png", "image/jpg", "image/jpeg"]; callback(null, allowedFileMimeTypes.includes(file.mimetype)); } }); const port = 8787; //The * in app.* needs to match the method type of the request app.get('/games', upload.none(), async (request, response) => { let result = {}; try { result = await games.getAllGames(request.query); } catch (error) { return response .status(500) //Error code when something goes wrong with the server .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({message: 'Something went wrong with the server.'}); } //Default response object response .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({'data': result}); }); app.get('/games/:id', upload.none(), async (request, response) => { console.log("Getting data for game " + request.params.id); let result = {}; try { result = await games.getGame(request.params.id); } catch (error) { return response .status(500) .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({message: 'Something went wrong with the server!'}) } response .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({'data': result}) }); app.get('/developers', upload.none(), async (request, response) => { let result = {}; try { result = await developers.getDeveloperNames(); } catch (error) { return response .status(500) //Error code when something goes wrong with the server .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({message: 'Something went wrong with the server.'}); } //Default response object response .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({'data': result}); }); app.get('/developers/:id', upload.none(), async (request, response) => { console.log("Getting data for developer " + request.params.id); let result = {}; try { result = await developers.getDeveloper(request.params.id); } catch (error) { return response .status(500) .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({message: 'Something went wrong with the server!'}) } response .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({'data': result}) }); app.get('/publishers', upload.none(), async (request, response) => { let result = {}; try { result = await publishers.getPublisherNames(); } catch (error) { return response .status(500) //Error code when something goes wrong with the server .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({message: 'Something went wrong with the server.'}); } //Default response object response .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({'data': result}); }); app.get('/publishers/:id', upload.none(), async (request, response) => { console.log("Getting data for publisher " + request.params.id); let result = {}; try { result = await publishers.getPublisher(request.params.id); } catch (error) { return response .status(500) .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({message: 'Something went wrong with the server!'}) } response .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({'data': result}) }); app.post('/games', upload.single('coverArt'), check('title', 'You must enter a title.').isLength({min: 3}), check('releaseDate', 'You must select a release date.').isDate(["YYYY-MM-DD"]), check('win', 'Invalid Windows option.').isIn([0, 1]), check('mac', 'Invalid MacOS option.').isIn([0, 1]), check('linux', 'Invalid Linux option.').isIn([0, 1]), check('shortDescription', 'You must enter a description'), checkSchema({ 'coverArt': { optional: true, custom: { options: (value, {req, path}) => !!req.file[path], errorMessage: 'Please upload an image file.', }, }, }), async (request, response) => { console.log(request.file); const errors = validationResult(request); if (!errors.isEmpty()) { return response .status(400) .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({ message: 'Request fields or files are invalid.', errors: errors.array(), }); } else { console.log(request.query); let result = {}; try { result = await games.addNewGame(request.query, request.file.filename); } catch (error) { console.log(error); return response .status(500) //Error code when something goes wrong with the server .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({message: 'Something went wrong with the server.'}); } response .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({message: 'Game added successfully!'}); } }); app.post('/developers', upload.none(), check('name', 'You must enter a name.').isLength({min: 3}), check('description', 'You must enter a description').isLength({min: 5}), check('homepage', 'You must enter a homepage URL.').isURL(), async (request, response) => { const errors = validationResult(request); if (!errors.isEmpty()) { return response .status(400) .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({ message: 'Request fields or files are invalid.', errors: errors.array(), }); } else { console.log(request.query); let result = {}; try { result = await developers.addNewDeveloper(request.query); } catch (error) { console.log(error); return response .status(500) //Error code when something goes wrong with the server .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({message: 'Something went wrong with the server.'}); } response .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({message: 'Developer added successfully!'}); } }); app.post('/publishers', upload.none(), check('name', 'You must enter a name.').isLength({min: 3}), check('description', 'You must enter a description').isLength({min: 5}), check('homepage', 'You must enter a homepage URL.').isURL(), async (request, response) => { const errors = validationResult(request); if (!errors.isEmpty()) { return response .status(400) .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({ message: 'Request fields or files are invalid.', errors: errors.array(), }); } else { console.log(request.query); let result = {}; try { result = await publishers.addNewPublisher(request.query); } catch (error) { console.log(error); return response .status(500) //Error code when something goes wrong with the server .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({message: 'Something went wrong with the server.'}); } response .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({message: 'Publisher added successfully!'}); } }); app.put('/games/:id', upload.single('coverArt'), check('title', 'You must enter a title.').isLength({min: 3}), check('releaseDate', 'You must select a release date.').isDate(["YYYY-MM-DD"]), check('win', 'Invalid Windows option.').isIn([0, 1]), check('mac', 'Invalid MacOS option.').isIn([0, 1]), check('linux', 'Invalid Linux option.').isIn([0, 1]), check('shortDescription', 'You must enter a description'), checkSchema({ 'coverArt': { optional: true, custom: { options: (value, {req, path}) => !!req.file[path], errorMessage: 'Please upload an image file.', }, }, }), async (request, response) => { const errors = validationResult(request); if (!errors.isEmpty()) { return response .status(400) .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({ message: 'Request fields or files are invalid.', errors: errors.array(), }); } else { console.log(request.query); let result = {}; try { result = await games.editGame(request.query.id, request.query, request.file.filename); } catch (error) { console.log(error); return response .status(500) //Error code when something goes wrong with the server .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({message: 'Something went wrong with the server.'}); } response .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({message: 'Game added successfully!'}); } }); app.delete('/games/:id', upload.none(), async (request, response) => { let result = {}; try { result = await games.deleteGame(request.query.id); } catch (error) { console.log(error); return response .status(500) //Error code when something goes wrong with the server .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({message: 'Something went wrong with the server.'}); } response .setHeader('Access-Control-Allow-Origin', '*') //Prevent CORS error .json({message: 'Game deleted successfully!'}); }); app.listen(port, () => { console.log(`Application listening at http://localhost:${port}`); })