Skip to content

Instantly share code, notes, and snippets.

@sang4lv
Last active December 21, 2015 00:19
Show Gist options
  • Save sang4lv/6218912 to your computer and use it in GitHub Desktop.
Save sang4lv/6218912 to your computer and use it in GitHub Desktop.
URL Shortener
var mongoose = require('mongoose');
var http = require('http');
mongoose.connect("mongodb://localhost/shortener");
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
var urlSchema = mongoose.Schema({
slug: String,
url: String
});
shortener = mongoose.model("shortener", urlSchema);
});
var server = http.createServer( function(httpRequest, httpResponse) {
var now = new Date();
var urls = httpRequest.url.split("/");
var parts = [];
for(var i = 0; i < urls.length; i += 1) {
if(urls[i] === "") continue;
parts.push(urls[i]);
}
if( parts.length === 0 ||
( parts.length === 1 && parts[0] === 'favicon.ico' ) ) {
console.log("replied with http 400");
httpResponse.writeHead( 400 );
httpResponse.end( "Invalid Request" );
} else if( parts.length === 2 ) {
//This is a set
shortener.find( {
url: parts[1]
}, function(error, oldUrl) {
if(error) throw error;
if(oldUrl.length === 0) {
var shortUrl = new shortener({
slug: now.getTime().toString(36),
url: decodeURIComponent(parts[1])
});
shortUrl.save( function(error, newUrl) {
var result = {
shortUrl: "http://" + httpRequest.headers.host + '/' + newUrl.slug
};
httpResponse.writeHead( 200, {
'Content-Type': 'application/json'
} );
httpResponse.end( JSON.stringify(result) );
} );
} else {
console.log("fetching old url");
console.log(oldUrl);
var result = {
shortUrl: "http://" + httpRequest.headers.host + '/' + oldUrl.slug
};
httpResponse.writeHead( 200, {
'Content-Type': 'application/json'
} );
httpResponse.end( JSON.stringify(result) );
}
} );
} else if( parts.length === 1 ) {
//This is a get
shortener.find( {
slug: parts[0]
}, function(error, oldUrl) {
console.log("redirect to url");
console.log(oldUrl[0].url);
httpResponse.writeHead( 302, {
'Location': oldUrl[0].url
} );
} );
}
} ).listen(7000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment