Implemented short code generation via nanoid

This commit is contained in:
Nicolai Ort 2021-08-12 19:33:59 +02:00
parent 97a86db5e3
commit 15508606a4
Signed by: niggl
GPG Key ID: 13AFA55AF62F269F
2 changed files with 39 additions and 3 deletions

View File

@ -12,6 +12,7 @@
"fastify": "^3.20.1",
"knex": "^0.21.21",
"level": "^7.0.0",
"nanoid": "^3.1.25",
"sqlite3": "^5.0.2"
},
"devDependencies": {

View File

@ -1,9 +1,10 @@
const fastify = require('fastify')({ logger: true })
const level = require('level')
const { nanoid } = require('nanoid')
const db = level('./db', { valueEncoding: 'json' })
// Declare a route
//Basic home route
fastify.get('/', async (request, reply) => {
return { hello: 'world' }
})
@ -18,6 +19,7 @@ fastify.get('/yt/:id', async (req, res) => {
res.redirect(302, `https://youtu.be/${req.params.id}`)
})
//Normal shorturls
fastify.get('/:id', async (req, res) => {
try {
const target = await db.get(req.params.id);
@ -28,9 +30,42 @@ fastify.get('/:id', async (req, res) => {
}
})
//Create new urls
fastify.post('/new', async (req, res) => {
console.log(req.body);
return "";
const target = req.body?.target;
let shortcode = req.body?.code;
if (!req.body?.target) {
res.statusCode = 400;
return "Missing target";
}
if (!shortcode) {
shortcode = nanoid(12);
}
else{
try {
const exists = await db.get(shortcode);
if(exists){
res.statusCode = 400;
return "Shortcode already exists, please choose another code";
}
} catch (error) {
if(!error.notFound){
res.statusCode=500;
return "Internal Server Error."
}
}
}
try {
await db.put(shortcode, target);
} catch (error) {
res.statusCode = 500;
return "DB ERROR";
}
return {
shortcode,
url: `http://localhost:3000/${shortcode}`,
target
};
})
// Run the server!