From 5636edd5b6af3486284b430f660b1b9e309a3671 Mon Sep 17 00:00:00 2001 From: Carson Fleming Date: Fri, 20 Oct 2023 23:37:28 -0400 Subject: Bring it all together and nitpick the appearance --- routes.js | 40 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) (limited to 'routes.js') diff --git a/routes.js b/routes.js index 012befe..207a022 100644 --- a/routes.js +++ b/routes.js @@ -4,10 +4,36 @@ const Url = require('./db/url-schema.js'); const utils = require('./utils.js'); const router = express.Router(); +async function createRoute(res, url, slug) { + try { + if (!utils.isUrlFormatted(url)) + return utils.sendBadRequestError(res, 'URL "'+url+'" is malformatted. Must be a valid URL.'); + if (!utils.isAlphaNumeric(slug)) + return utils.sendBadRequestError(res, 'Slug "'+slug+'" is malformatted. Must be alphanumeric.'); + + slug = slug.toLowerCase(); + if (await Url.exists({slug: slug})) + return utils.sendBadRequestError(res, 'Slug "'+slug+'" already exists. Updates are not supported at this time.'); + + await new Url({url, slug}).save(); + utils.sendSuccessfulSlugCreation(res, slug); + } catch (err) { + utils.sendInternalServerError(res, err); + } +} + router.get('/', async (req, res) => { utils.sendFile(res, 'static/index.html'); }); +router.post('/', async (req, res) => { + let slug; + do { + slug = utils.generateSlug(); + } while (await Url.exists({slug: slug})); + await createRoute(res, req.body.url, slug); +}); + router.get('/:slug', async (req, res) => { try { const url = await Url.findOne({slug: req.params.slug.toLowerCase()}); @@ -16,12 +42,22 @@ router.get('/:slug', async (req, res) => { else utils.sendNotFoundError(res); } catch (err) { - utils.sendInternalServerError(res); + utils.sendInternalServerError(res, err); } }); -router.all('/*', async (req, res) => { +router.put('/:slug', async (req, res) => { + if (!req.params.slug) + return utils.sendBadRequestError(res, 'Cannot PUT to root path.'); + await createRoute(res, req.body.url, req.params.slug.toLowerCase()); +}); + +router.get('/*', async (req, res) => { utils.sendNotFoundError(res); }); +router.all('/*', async (req, res) => { + utils.sendBadRequestError(res, 'Nothing exists at this endpoint.'); +}); + module.exports = router; -- cgit v1.2.3