Migrated to knex
This commit is contained in:
@@ -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!
|
||||
|
||||
Reference in New Issue
Block a user