linkylinky/src/server.js

45 lines
1.0 KiB
JavaScript

const fastify = require('fastify')({ logger: true })
const level = require('level')
const db = level('./db', { valueEncoding: 'json' })
// Declare a route
fastify.get('/', async (request, reply) => {
return { hello: 'world' }
})
//Automagic Amazn redirects on /a/
fastify.get('/a/:id', async (req, res) => {
res.redirect(302, `https://amazon.de/dp/${req.params.id}`)
})
//Automagic Youtube redirects on /yt/
fastify.get('/yt/:id', async (req, res) => {
res.redirect(302, `https://youtu.be/${req.params.id}`)
})
fastify.get('/:id', async (req, res) => {
try {
const target = await db.get(req.params.id);
res.redirect(302, target);
} catch (error) {
res.statusCode = 404;
return 404;
}
})
fastify.post('/new', async (req, res) => {
console.log(req.body);
return "";
})
// Run the server!
const start = async () => {
try {
await fastify.listen(3000)
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()