Added comments
This commit is contained in:
parent
2464573525
commit
52cf92b5e5
|
@ -38,6 +38,8 @@ fastify.get('/yt/:id', async (req, res) => {
|
|||
//Normal shorturls
|
||||
fastify.get('/:shortcode', async (req, res) => {
|
||||
const shortcode = req.params.shortcode;
|
||||
|
||||
//This should never happen but better safe than 500
|
||||
if (!shortcode) {
|
||||
return 404;
|
||||
}
|
||||
|
@ -51,7 +53,7 @@ fastify.get('/:shortcode', async (req, res) => {
|
|||
res.redirect(302, target[0].target)
|
||||
})
|
||||
|
||||
//Create new urls
|
||||
//Create new url schema
|
||||
const newUrlSchema = {
|
||||
body: {
|
||||
type: 'object',
|
||||
|
@ -62,14 +64,22 @@ const newUrlSchema = {
|
|||
}
|
||||
};
|
||||
|
||||
//Create new url route
|
||||
fastify.post('/new', { newUrlSchema }, async (req, res) => {
|
||||
const target = req.body?.target;
|
||||
let shortcode = req.body?.shortcode;
|
||||
|
||||
//Check if the user provided a target
|
||||
if (!target) {
|
||||
res.statusCode = 400;
|
||||
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) {
|
||||
const exists = await knex.select('shortcode')
|
||||
.from('urls')
|
||||
|
@ -85,6 +95,11 @@ fastify.post('/new', { newUrlSchema }, async (req, res) => {
|
|||
}
|
||||
shortcode = uniqid();
|
||||
}
|
||||
/**
|
||||
* If a custom shortcode is provided: Check for collisions.
|
||||
* Collision detected: Warn user
|
||||
* No collision: Proceed to db entry creation
|
||||
*/
|
||||
else {
|
||||
const exists = await knex.select('shortcode')
|
||||
.from('urls')
|
||||
|
@ -95,6 +110,8 @@ fastify.post('/new', { newUrlSchema }, async (req, res) => {
|
|||
return "Shortcode already exists, please choose another code";
|
||||
}
|
||||
}
|
||||
|
||||
//Create a new db entry
|
||||
await knex('urls').insert({target, shortcode});
|
||||
|
||||
return {
|
||||
|
|
Loading…
Reference in New Issue