diff --git a/src/server.js b/src/server.js index 7a98aa9..269384e 100644 --- a/src/server.js +++ b/src/server.js @@ -35,7 +35,7 @@ fastify.get('/a/:id', async (req, res) => { fastify.get('/yt/:id', async (req, res) => { res.redirect(302, `https://youtu.be/${req.params.id}`) }) -//Automagic Youtube redirects on /ytpl/ +//Automagic Youtube Playlist redirects on /ytpl/ fastify.get('/ytpl/:id', async (req, res) => { res.redirect(302, `https://youtube.com/playlist?list=${req.params.id}`) }) @@ -69,8 +69,8 @@ const newUrlSchema = { } }; -//Create new url route -fastify.post('/api/new', { newUrlSchema }, async (req, res) => { +//Create new url api route +fastify.post('/api', { newUrlSchema }, async (req, res) => { const target = req.body?.target; let shortcode = req.body?.shortcode; @@ -132,13 +132,37 @@ fastify.post('/api/new', { newUrlSchema }, async (req, res) => { } }); +//Get url api route +fastify.get('/api/:shortcode', async (req, res) => { + const shortcode = req.params.shortcode; + + //This should never happen but better safe than 500 + if (!shortcode) { + return 404; + } + + const exists = await knex.select('shortcode', 'target') + .from('urls') + .where('shortcode', '=', shortcode) + .limit(1); + if (exists.length == 0) { + return 404; + } + + return { + url: `${config.getBaseUrl()}/${exists[0].shortcode}`, + shortcode: exists[0].shortcode, + target: exists[0].target + } +}); + /** * Checks for some default providers with custom url schemes (amazon and youtube r/n) * @param {string} target The target URL * @returns Standard shortening response if provider recognized or null */ function checkKnownProviders(target) { - target=decodeURIComponent(target); + target = decodeURIComponent(target); const youtubeVideoID = target.match(/(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/) if (youtubeVideoID) { const shortcode = `yt/${youtubeVideoID[1]}`