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(); const compression = require('compression'); logger.level = 'debug'; // grab the url model const Url = require('./models/url'); let isProduction = false; let sitePath = 'public'; let index = 'views/index.html'; process.env.NODE_ENV = process.env.NODE_ENV || 'dev'; if (process.env.NODE_ENV === 'prod') { isProduction = true; sitePath = 'live'; index = 'dist/index.html' } logger.warn(`isProduction:${isProduction}`); mongoose.connect('mongodb://' + config.db.host + '/' + config.db.name); app.use(compression()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static(path.join(__dirname, sitePath))); 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, index)); }); 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(`Redirect: ${doc.long_url}`); res.redirect(doc.long_url); } else { res.redirect(config.webhost); } }); }); const server = app.listen(config.port, function () { logger.info(`Server listening on port ${config.port}`); });