initial
This commit is contained in:
66
routes.js
Normal file
66
routes.js
Normal file
@@ -0,0 +1,66 @@
|
||||
const Joi = require('joi');
|
||||
const mongoose = require('mongoose');
|
||||
const Schema = mongoose.Schema;
|
||||
const hash = require('./hash');
|
||||
const HASHLEN = 7;
|
||||
|
||||
const baseUrl = process.env.BASE_URL || 'shrt.in';
|
||||
|
||||
const schema = new Schema({
|
||||
shrt: String,
|
||||
url: String,
|
||||
});
|
||||
const Shrt = mongoose.model('Shrt', schema);
|
||||
|
||||
module.exports = [
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/',
|
||||
handler(request, reply) {
|
||||
reply.file('views/index.html');
|
||||
}
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/public/{file}',
|
||||
handler(request, reply) {
|
||||
reply.file(`public/${request.params.file}`);
|
||||
}
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/new',
|
||||
handler(request, reply) {
|
||||
const uid = hash(HASHLEN);
|
||||
const r = new Shrt({
|
||||
short: `${baseUrl}/${uniqueID}`,
|
||||
url: request.payload.url,
|
||||
});
|
||||
|
||||
r.save((err, redir) => err ? reply(err) : reply(redir));
|
||||
},
|
||||
config: {
|
||||
validate: {
|
||||
payload: {
|
||||
url: Joi.string()
|
||||
.regex(/^https?:\/\/([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/)
|
||||
.required()
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path:'/{hash}',
|
||||
handler(request, reply) {
|
||||
const query = {
|
||||
'short': `${baseUrl}/${request.params.hash}`
|
||||
};
|
||||
Shrt.findOne(query, (err, shrt) => {
|
||||
if (err) return reply(err);
|
||||
else if (shrt) reply().redirect(shrt.url);
|
||||
else reply.file('views/404.html').code(404);
|
||||
});
|
||||
}
|
||||
},
|
||||
];
|
Reference in New Issue
Block a user