Migrated to knex

This commit is contained in:
Nicolai Ort 2021-08-12 20:13:46 +02:00
parent 9f80ad2941
commit 823b211c8c
Signed by: niggl
GPG Key ID: 13AFA55AF62F269F
2 changed files with 69 additions and 28 deletions

28
knexfile.js Normal file
View File

@ -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'
}
}
};

View File

@ -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!