nurl/app.js
Martin Donnelly 1209271cd4 Re work
2017-08-05 21:14:17 +01:00

94 lines
2.4 KiB
JavaScript

const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const config = require('./config');
const base58 = require('./base58.js');
const log4js = require('log4js');
const logger = log4js.getLogger();
logger.level = 'debug';
// grab the url model
const Url = require('./models/url');
mongoose.connect('mongodb://' + config.db.host + '/' + config.db.name);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.all('/*', function(req, res, next) {
// CORS headers
res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
// Set custom headers for CORS
res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key');
if (req.method == 'OPTIONS') {
res.status(200).end();
} else {
next();
}
});
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, 'views/index.html'));
});
app.post('/api/v1/shorten', function(req, res){
const longUrl = req.body.url;
let shortUrl = '';
// check if url already exists in database
Url.findOne({long_url: longUrl}, function (err, doc){
if (doc){
shortUrl = config.webhost + base58.encode(doc._id);
// the document exists, so we return it without creating a new entry
res.send({'shortUrl': shortUrl});
} else {
// since it doesn't exist, let's go ahead and create it:
const newUrl = Url({
long_url: longUrl
});
// save the new link
newUrl.save(function(err) {
if (err){
logger.error(err);
}
shortUrl = config.webhost + base58.encode(newUrl._id);
res.send({'shortUrl': shortUrl});
});
}
});
});
app.get('/:encoded_id', function(req, res){
const base58Id = req.params.encoded_id;
const id = base58.decode(base58Id);
// check if url already exists in database
Url.findOneAndUpdate({_id: id}, {$inc:{visits:1}}, function (err, doc){
if (doc) {
logger.debug('doc', doc);
res.redirect(doc.long_url);
} else {
res.redirect(config.webhost);
}
});
});
const server = app.listen(3000, function () {
logger.info('Server listening on port 3000');
});