diff --git a/knexfile.js b/knexfile.js new file mode 100644 index 0000000..377e830 --- /dev/null +++ b/knexfile.js @@ -0,0 +1,28 @@ +// Update with your config settings. + +module.exports = { + + development: { + client: 'sqlite3', + connection: { + filename: './dev.sqlite3' + } + }, + + production: { + client: 'postgresql', + connection: { + database: 'my_db', + user: 'username', + password: 'password' + }, + pool: { + min: 2, + max: 10 + }, + migrations: { + tableName: 'knex_migrations' + } + } + +}; diff --git a/src/server.js b/src/server.js index 5904fa2..dd74a13 100644 --- a/src/server.js +++ b/src/server.js @@ -1,8 +1,11 @@ const fastify = require('fastify')({ logger: true }) -const level = require('level') const { nanoid } = require('nanoid') - -const db = level('./db', { valueEncoding: 'json' }) +const knex = require('knex')({ + client: 'sqlite3', + connection: { + filename: "./dev.sqlite3" + } +}); //Basic home route fastify.get('/', async (request, reply) => { @@ -20,14 +23,19 @@ fastify.get('/yt/:id', async (req, res) => { }) //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; +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 @@ -48,34 +56,39 @@ fastify.post('/new', { newUrlSchema }, async (req, res) => { 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 { - 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." - } + 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"; } } - try { - await db.put(shortcode, target); - } catch (error) { - res.statusCode = 500; - return "DB ERROR"; - } + await knex('urls').insert({target, shortcode}); + return { + url: `http://localhost:3000${shortcode}`, shortcode, - url: `http://localhost:3000/${shortcode}`, target - }; + } }) // Run the server!