diff --git a/src/server.js b/src/server.js index be97479..e33da94 100644 --- a/src/server.js +++ b/src/server.js @@ -3,6 +3,7 @@ var uniqid = require('uniqid'); require('dotenv').config(); const argon2 = require('argon2'); const isBot = require('isbot') +const { makeBadge, ValidationError } = require('badge-maker') let config = { domain: process.env.DOMAIN || "localhost:3000", @@ -259,6 +260,40 @@ fastify.get('/api/:shortcode', async (req, res) => { } }); +//Get url api route +fastify.get('/api/badge/:shortcode', async (req, res) => { + const shortcode = req.params.shortcode; + const label = req.query.label || 'vists'; + const color = req.query.color || 'green'; + const style = req.query.style || 'for-the-badge'; + + //This should never happen but better safe than 500 + if (!shortcode) { + return 404; + } + + const exists = await knex.select('shortcode', 'target', 'no_preview', 'clientside') + .from('urls') + .where('shortcode', '=', shortcode) + .limit(1); + if (exists.length == 0) { + return 404; + } + + const visits = await knex.select('timestamp') + .from('visits') + .where('shortcode', '=', shortcode); + + const format = { + label, + message: visits.length.toString(), + color, + style + } + + res.type('image/svg+xml') + return makeBadge(format); +}); //User registration fastify.post('/api/auth/register', async (req, res) => {