const fastify = require('fastify')({ logger: true }) const { nanoid } = require('nanoid') const knex = require('knex')({ client: 'sqlite3', connection: { filename: "./dev.sqlite3" } }); //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('/:shortcode', async (req, res) => { const shortcode = req.params.shortcode; if (!shortcode) { return 404; } const target = await knex.select('target') .from('urls') .where('shortcode', '=', shortcode) .limit(1); if (!target[0]) { return 404 } res.redirect(302, target[0].target) }) //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) { const exists = await knex.select('shortcode') .from('urls') .where('target', '=', target) .limit(1); if (exists.length != 0) { shortcode = exists[0].shortcode; return { url: `http://localhost:3000/${shortcode}`, shortcode, target } } shortcode = nanoid(12); } else { const exists = await knex.select('shortcode') .from('urls') .where('shortcode', '=', shortcode) .limit(1); if (exists.length != 0) { res.statusCode = 400; return "Shortcode already exists, please choose another code"; } } await knex('urls').insert({target, shortcode}); return { url: `http://localhost:3000${shortcode}`, shortcode, target } }) // Run the server! const start = async () => { try { await fastify.listen(3000) } catch (err) { fastify.log.error(err) process.exit(1) } } start()