wip pre moving from bower to browserfy

This commit is contained in:
Martin Donnelly 2017-09-25 17:48:55 +01:00
parent d25b1a247a
commit 445a0c0411
5 changed files with 68 additions and 70 deletions

View File

@ -12,35 +12,44 @@
"es6": true "es6": true
}, },
"rules": { "rules": {
"no-new-object": 1, "arrow-spacing": "error",
"no-reserved-keys": 1, "block-scoped-var": "error",
"no-array-constructor": 1, "block-spacing": "error",
"quotes": [1, "single"], "brace-style": ["error", "stroustrup", {}],
"max-len": [1, 120, 2], // 2 spaces per tab, max 80 chars per line "camelcase": "error",
"no-inner-declarations": [1, "both"], "comma-dangle": ["error", "never"],
"no-shadow-restricted-names": 1, "comma-spacing": ["error", { "before": false, "after": true }],
"one-var": 0, "comma-style": [1, "last"],
"vars-on-top": 1, "consistent-this": [1, "_this"],
"eqeqeq": 1,
"curly": [1, "multi"], "curly": [1, "multi"],
"eol-last": 1,
"eqeqeq": 1,
"func-names": 1,
"indent": ["error", 2, { "SwitchCase": 1 }],
"lines-around-comment": ["error", { "beforeBlockComment": true, "allowArrayStart": true }],
"max-len": [1, 120, 2], // 2 spaces per tab, max 80 chars per line
"new-cap": 1,
"newline-before-return": "error",
"no-array-constructor": 1,
"no-inner-declarations": [1, "both"],
"no-mixed-spaces-and-tabs": 1, "no-mixed-spaces-and-tabs": 1,
"no-multi-spaces": 2,
"no-new-object": 1,
"no-shadow-restricted-names": 1,
"object-curly-spacing": ["error", "always"],
"padded-blocks": ["error", { "blocks": "never", "switches": "always" }],
"prefer-const": "error",
"prefer-template": "error",
"one-var": 0,
"quote-props": ["error", "always"],
"quotes": [1, "single"],
"radix": 1,
"semi": [1, "always"],
"space-before-blocks": [1, "always"], "space-before-blocks": [1, "always"],
"space-infix-ops": 1, "space-infix-ops": 1,
"eol-last": 1, "vars-on-top": 1,
"comma-style": [1, "last"], "no-multiple-empty-lines": ["error", { "max": 1, "maxEOF": 1 }],
"no-comma-dangle": 1, "spaced-comment": ["error", "always", { "markers": ["/"] }]
"semi": [1, "always"],
"radix": 1,
"camelcase": 1,
"new-cap": 1,
"consistent-this": [1, "_this"],
"func-names": 1,
"no-multi-spaces": 2,
"brace-style": [2,"1tbs",{}],
"indent": [2,2],
"comma-spacing": ["error", { "before": false, "after": true }],
"object-curly-spacing": ["error", "always"]
} }
} }

31
app.js
View File

@ -18,7 +18,7 @@ const Url = require('./models/url');
let isProduction = false; let isProduction = false;
let sitePath = 'public'; let sitePath = 'public';
let indexView = 'views/index.html'; let indexView = 'views/index.html';
let listView = 'views/list.html'; const listView = 'views/list.html';
process.env.NODE_ENV = process.env.NODE_ENV || 'dev'; process.env.NODE_ENV = process.env.NODE_ENV || 'dev';
@ -31,14 +31,13 @@ if (process.env.NODE_ENV === 'prod') {
logger.warn(`isProduction:${isProduction}`); logger.warn(`isProduction:${isProduction}`);
mongoose.connect(`mongodb://${ config.db.host }/${ config.db.name}`);
mongoose.connect('mongodb://' + config.db.host + '/' + config.db.name);
app.use(compression()); app.use(compression());
app.use(bodyParser.json()); app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.urlencoded({ 'extended': true }));
app.use(express.static(path.join(__dirname, sitePath))); app.use(express.static(path.join(__dirname, sitePath)));
app.use(favicon(__dirname + '/live/favicon-16x16.png')); app.use(favicon(`${__dirname }/live/favicon-16x16.png`));
app.all('/*', (req, res, next) => { app.all('/*', (req, res, next) => {
// CORS headers // CORS headers
@ -50,7 +49,6 @@ app.all('/*', (req, res, next) => {
res.status(200).end(); res.status(200).end();
else else
next(); next();
}); });
app.get('/', function(req, res) { app.get('/', function(req, res) {
@ -66,17 +64,17 @@ function postShort(req, res) {
let shortUrl = ''; let shortUrl = '';
// check if url already exists in database // check if url already exists in database
Url.findOne({ long_url: longUrl }, (err, doc) => { Url.findOne({ 'long_url': longUrl }, (err, doc) => {
if (doc) { if (doc) {
shortUrl = config.webhost + base58.encode(doc._id); shortUrl = config.webhost + base58.encode(doc._id);
// the document exists, so we return it without creating a new entry // the document exists, so we return it without creating a new entry
res.send({ 'shortUrl': shortUrl }); res.send({ 'shortUrl': shortUrl });
} else { }
else {
// since it doesn't exist, let's go ahead and create it: // since it doesn't exist, let's go ahead and create it:
const newUrl = Url({ const newUrl = Url({
long_url: longUrl 'long_url': longUrl
}); });
// save the new link // save the new link
@ -84,15 +82,12 @@ function postShort(req, res) {
if (err) if (err)
logger.error(err); logger.error(err);
shortUrl = config.webhost + base58.encode(newUrl._id); shortUrl = config.webhost + base58.encode(newUrl._id);
res.send({ 'shortUrl': shortUrl }); res.send({ 'shortUrl': shortUrl });
}); });
} }
}); });
} }
function getList(req, res) { function getList(req, res) {
@ -103,28 +98,24 @@ function getList(req, res) {
} }
function getEncodedID(req, res) { function getEncodedID(req, res) {
const base58Id = req.params.encoded_id; const base58Id = req.params.encoded_id;
const id = base58.decode(base58Id); const id = base58.decode(base58Id);
// check if url already exists in database // check if url already exists in database
Url.findOneAndUpdate({ _id: id }, { $inc: { visits: 1 } }, (err, doc) => { Url.findOneAndUpdate({ '_id': id }, { '$inc': { 'visits': 1 } }, (err, doc) => {
if (doc) { if (doc) {
logger.debug(`Redirect: ${doc.long_url}`); logger.debug(`Redirect: ${doc.long_url}`);
res.redirect(doc.long_url); res.redirect(doc.long_url);
} else }
else
res.redirect(config.webhost); res.redirect(config.webhost);
}); });
} }
app.post('/api/v1/shorten', postShort); app.post('/api/v1/shorten', postShort);
app.get('/api/v1/list', getList); app.get('/api/v1/list', getList);
app.get('/:encoded_id', getEncodedID); app.get('/:encoded_id', getEncodedID);
const server = app.listen(config.port, () => { const server = app.listen(config.port, () => {
logger.info(`Server listening on port ${config.port}`); logger.info(`Server listening on port ${config.port}`);
}); });

View File

@ -3,22 +3,22 @@ const alphabet = 'bMJZSrnxEyq8kN3UYQL5oXwV7BCFRtvpmDf1shAuHzKicTjeG29Pg4adW6';
const base = alphabet.length; const base = alphabet.length;
function encode(num){ function encode(num) {
let encoded = ''; let encoded = '';
while (num){ while (num) {
const remainder = num % base; const remainder = num % base;
num = Math.floor(num / base); num = Math.floor(num / base);
encoded = alphabet[remainder].toString() + encoded; encoded = alphabet[remainder].toString() + encoded;
} }
return encoded; return encoded;
} }
function decode(str){ function decode(str) {
let decoded = 0; let decoded = 0;
while (str){ while (str) {
const index = alphabet.indexOf(str[0]); const index = alphabet.indexOf(str[0]);
const power = str.length - 1; const power = str.length - 1;
decoded += index * (Math.pow(base, power)); decoded += index * (Math.pow(base, power));
str = str.substring(1); str = str.substring(1);
} }
return decoded; return decoded;

View File

@ -2,23 +2,23 @@ const mongoose = require('mongoose');
const Schema = mongoose.Schema; const Schema = mongoose.Schema;
const CounterSchema = Schema({ const CounterSchema = Schema({
_id: { type: String, required: true }, '_id': { 'type': String, 'required': true },
seq: { type: Number, default: 1000 } 'seq': { 'type': Number, 'default': 1000 }
}); });
const counter = mongoose.model('counter', CounterSchema); const counter = mongoose.model('counter', CounterSchema);
// create a schema for our links // create a schema for our links
const urlSchema = new Schema({ const urlSchema = new Schema({
_id: { type: Number, index: true }, '_id': { 'type': Number, 'index': true },
long_url: String, 'long_url': String,
created_at: Date, 'created_at': Date,
visits: { type: Number, default: 0 } 'visits': { 'type': Number, 'default': 0 }
}); });
urlSchema.pre('save', function(next) { urlSchema.pre('save', function(next) {
const doc = this; const doc = this;
counter.findByIdAndUpdate({ _id: 'url_count' }, { $inc: { seq: 1 } }, function(error, counter) { counter.findByIdAndUpdate({ '_id': 'url_count' }, { '$inc': { 'seq': 1 } }, function(error, counter) {
if (error) if (error)
return next(error); return next(error);
doc.created_at = new Date(); doc.created_at = new Date();

View File

@ -1,16 +1,15 @@
function shorten() { function shorten() {
$.ajax({ $.ajax({
url: '/api/v1/shorten', 'url': '/api/v1/shorten',
type: 'POST', 'type': 'POST',
dataType: 'JSON', 'dataType': 'JSON',
data: { url: $('#url-field').val() }, 'data': { 'url': $('#url-field').val() },
success: data => { 'success': data => {
console.log('data', data); console.log('data', data);
const $link = $('#link'); const $link = $('#link');
const resultHTML = `<a class="result" href="${data.shortUrl}">${data.shortUrl}</a>`; const resultHTML = `<a class="result" href="${data.shortUrl}">${data.shortUrl}</a>`;
$link.html(resultHTML); $link.html(resultHTML);
$link.hide().fadeIn('slow'); $link.hide().fadeIn('slow');
} }
}); });
} }
@ -18,7 +17,6 @@ function shorten() {
$('#url-field').keyup( (event) => { $('#url-field').keyup( (event) => {
if(event.keyCode === 13) if(event.keyCode === 13)
$('#btn-shorten').click(); $('#btn-shorten').click();
}); });
$('#btn-shorten').on('click', () => { $('#btn-shorten').on('click', () => {