Added comments

This commit is contained in:
Nicolai Ort 2021-08-12 21:21:23 +02:00
parent 2464573525
commit 52cf92b5e5
Signed by: niggl
GPG Key ID: 13AFA55AF62F269F
1 changed files with 18 additions and 1 deletions

View File

@ -38,6 +38,8 @@ fastify.get('/yt/:id', async (req, res) => {
//Normal shorturls //Normal shorturls
fastify.get('/:shortcode', async (req, res) => { fastify.get('/:shortcode', async (req, res) => {
const shortcode = req.params.shortcode; const shortcode = req.params.shortcode;
//This should never happen but better safe than 500
if (!shortcode) { if (!shortcode) {
return 404; return 404;
} }
@ -51,7 +53,7 @@ fastify.get('/:shortcode', async (req, res) => {
res.redirect(302, target[0].target) res.redirect(302, target[0].target)
}) })
//Create new urls //Create new url schema
const newUrlSchema = { const newUrlSchema = {
body: { body: {
type: 'object', type: 'object',
@ -62,14 +64,22 @@ const newUrlSchema = {
} }
}; };
//Create new url route
fastify.post('/new', { newUrlSchema }, async (req, res) => { fastify.post('/new', { newUrlSchema }, async (req, res) => {
const target = req.body?.target; const target = req.body?.target;
let shortcode = req.body?.shortcode; let shortcode = req.body?.shortcode;
//Check if the user provided a target
if (!target) { if (!target) {
res.statusCode = 400; res.statusCode = 400;
return "Missing target"; return "Missing target";
} }
/**
* If no custom shortcode is provided: Check if a code for the target already exists.
* If it exists: No new get's generated => The existing code get's used.
* If it doesn't exist: Generate a new code and proceed to creating a new db entry.
*/
if (!shortcode) { if (!shortcode) {
const exists = await knex.select('shortcode') const exists = await knex.select('shortcode')
.from('urls') .from('urls')
@ -85,6 +95,11 @@ fastify.post('/new', { newUrlSchema }, async (req, res) => {
} }
shortcode = uniqid(); shortcode = uniqid();
} }
/**
* If a custom shortcode is provided: Check for collisions.
* Collision detected: Warn user
* No collision: Proceed to db entry creation
*/
else { else {
const exists = await knex.select('shortcode') const exists = await knex.select('shortcode')
.from('urls') .from('urls')
@ -95,6 +110,8 @@ fastify.post('/new', { newUrlSchema }, async (req, res) => {
return "Shortcode already exists, please choose another code"; return "Shortcode already exists, please choose another code";
} }
} }
//Create a new db entry
await knex('urls').insert({target, shortcode}); await knex('urls').insert({target, shortcode});
return { return {