linkylinky/src/server.js

90 lines
2.2 KiB
JavaScript

const fastify = require('fastify')({ logger: true })
const level = require('level')
const { nanoid } = require('nanoid')
const db = level('./db', { valueEncoding: 'json' })
//Basic home route
fastify.get('/', async (request, reply) => {
return { hello: 'world' }
})
//Automagic Amazn redirects on /a/
fastify.get('/a/:id', async (req, res) => {
res.redirect(302, `https://amazon.de/dp/${req.params.id}`)
})
//Automagic Youtube redirects on /yt/
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);
res.redirect(302, target);
} catch (error) {
res.statusCode = 404;
return 404;
}
})
//Create new urls
const newUrlSchema = {
body: {
type: 'object',
properties: {
target: { type: 'string' },
shortcode: { type: 'string' },
}
}
};
fastify.post('/new', { newUrlSchema }, async (req, res) => {
const target = req.body?.target;
let shortcode = req.body?.shortcode;
if (!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!
const start = async () => {
try {
await fastify.listen(3000)
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()