url-shortener/src/service/redirect.js
2022-09-05 19:03:58 +02:00

40 lines
1.1 KiB
JavaScript

const express = require('express')
const path = require('path');
const main = require('../main');
const router = express.Router()
const Url = require('../models/url')
// : app.get(/:code)
// @route GET /:code
// @description Redirect to the long/original URL
router.get('/:code', async (req, res) => {
try {
// find a document match to the code in req.params.code
const url = await Url.findOne({
urlCode: req.params.code
})
if (url) {
// when valid we perform a redirect
main.logger.info("Redirecting to: " + url.longUrl)
return res.redirect(url.longUrl)
} else {
main.logger.info("Redirecting to Home.")
return res.sendFile(path.join(__dirname + `../../../public/index.html`))
// else return a not found 404 status
//return res.status(404).json('No URL Found')
}
}
// exception handler
catch (err) {
main.logger.error(err)
res.status(500).json('Server Error')
}
})
module.exports = router