summaryrefslogtreecommitdiff
path: root/routes.js
diff options
context:
space:
mode:
authorCarson Fleming <cflems@cflems.net>2023-10-20 23:37:28 -0400
committerCarson Fleming <cflems@cflems.net>2023-10-20 23:37:28 -0400
commit5636edd5b6af3486284b430f660b1b9e309a3671 (patch)
treef065d63d75ba3aa08eefa51c2cab407dcac859c6 /routes.js
parent5b4f8c220bbcbe1ee4b684f91db7cc419e423a41 (diff)
downloadfle.ms-5636edd5b6af3486284b430f660b1b9e309a3671.tar.gz
Bring it all together and nitpick the appearance
Diffstat (limited to 'routes.js')
-rw-r--r--routes.js40
1 files changed, 38 insertions, 2 deletions
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;