diff --git a/lib/index.js b/lib/index.js index 2479979..40951c6 100644 --- a/lib/index.js +++ b/lib/index.js @@ -5,6 +5,7 @@ const path = require('path') const crawl = require('./crawler') const parseHTML = require('./parser') const generateICS = require('./ics') +const { genericErrorHandler, checkFBURL } = require('./middlewares') const port = process.env.PORT const app = express() @@ -21,18 +22,16 @@ app.get('*', (req, res) => { res.status(400).render('404') }) +app.get('/error', (req, res) => { + res + .status(500) + .render('error', { error: req.error || '' }) +}) + +app.use('/download', checkFBURL) app.post('/download', async (req, res) => { const { url } = req.body - if (!/facebook/.test(url)) { - return res - .status(500) - .render( - 'error', - { error: 'Not Facebook URL!' } - ) - } - try { const html = await crawl(url) const data = parseHTML(html) @@ -44,15 +43,12 @@ app.post('/download', async (req, res) => { .send(200, new Buffer(ics, 'utf8')) } } catch (err) { - console.error(err) - return res - .status(500) - .render('error', { error: err.toString() }) + return next(err) } - - return res.render('download', { url }) }) +app.use(genericErrorHandler) + app.listen(port, () => { console.log(`App running on port ${port}`) }) diff --git a/lib/middlewares.js b/lib/middlewares.js new file mode 100644 index 0000000..41758ef --- /dev/null +++ b/lib/middlewares.js @@ -0,0 +1,33 @@ +const FBURLError = () => new Error('Not a valid Facebook URL!') + +const genericErrorHandler = (err, req, res, next) => { + console.error(err.stack) + res + .status(500) + .render('error', { error: err.toString() }) +} + +const checkFBURL = (req, res, next) => { + const { url } = req.body + + if (!url) { + return next(FBURLError()) + } + + try { + const FBURL = new URL(url) + if (!(/facebook/.test(FBURL.hostname))) { + return next(FBURLError()) + } + } catch (err) { + return next(err) + } + + + return next() +} + +module.exports = { + genericErrorHandler, + checkFBURL, +} diff --git a/lib/parser.js b/lib/parser.js index 5e3506e..aff473a 100644 --- a/lib/parser.js +++ b/lib/parser.js @@ -84,7 +84,6 @@ const parseHTML = (html) => { {} const data = parseEventData(eventData) - console.log(data) return data } catch (err) { throw err