Permalink
Browse files

checking for dupes

  • Loading branch information...
1 parent 5010a55 commit e743e027e8f8bb5721ee8b2bf11a5d9cdb2ecc00 Edward Hotchkiss committed Sep 27, 2011
Showing with 38 additions and 15 deletions.
  1. +2 −2 examples/basic.js
  2. +22 −11 lib/short.js
  3. +12 −0 models/ShortURL.js
  4. +2 −2 package.json
View
@@ -1,6 +1,6 @@
var mongoose = require("mongoose");
-var short = require("../");
+var short = require("short");
mongoose.connect("mongodb://localhost/short");
@@ -18,7 +18,7 @@ short.make(URL, function(error, shortURL) {
var hash = shortURLObject[0].hash;
console.log(URL, hash);
process.exit(1);
- }
+ };
});
}
});
View
@@ -2,29 +2,40 @@
(function(global, undefined) {
var mongoose = require("mongoose");
var base = require("base-converter");
- var shortURL = require("../models/ShortURL.js");
+ var ShortURL = require("../models/ShortURL.js").ShortURL;
function hesher(URL) {
- var id = Math.floor(Math.random() * (100000 - 999000 + 1) + 999000);
- var hash = base.decTo36(id);
+ var id = Math.floor(Math.random() * (100000 - 9999999 + 1) + 9999999);
+ var hash = base.decTo62(id);
return hash;
};
var short = function(){};
short.make = function(URL, callback) {
var hashedURL = hesher(URL);
- var shortURLItem = new shortURL.ShortURL({
- URL : URL,
- hash : hashedURL
- });
- shortURLItem.save(function(error, item) {
+ ShortURL.checkExists(hashedURL, function(error, count) {
if (error) {
callback(error, null);
} else {
- callback(null, item);
- };
+ if (count === 0) {
+ var shortURLItem = new ShortURL({
+ URL : URL,
+ hash : hashedURL
+ });
+ shortURLItem.save(function(error, item) {
+ if (error) {
+ callback(error, null);
+ } else {
+ callback(null, item);
+ };
+ });
+ } else {
+ console.log("taken ...");
+ short.make(URL, callback);
+ }
+ }
});
};
short.get = function(hash, callback) {
- shortURL.ShortURL.findByHash(hash, function(error, URL) {
+ ShortURL.findByHash(hash, function(error, URL) {
if (error) {
callback(error, null);
} else {
View
@@ -21,6 +21,18 @@ var shortURL_schema = {
var ShortURLSchema = new Schema(shortURL_schema);
var ShortURL = mongoose.model("ShortURL", ShortURLSchema);
+ShortURL.checkExists = function(hash, callback) {
+ var query = ShortURL.find({});
+ query.where("hash", hash);
+ query.exec(function(error, shortenedURLS) {
+ if (error) {
+ callback(error, null);
+ } else {
+ callback(null, shortenedURLS.length);
+ }
+ });
+};
+
ShortURL.findByHash = function(hash, callback) {
ShortURL.find({ hash: hash }, function(error, URL) {
if (error) {
View
@@ -1,8 +1,8 @@
{
"author": "Edward Hotchkiss <e@ingk.com>",
"name": "short",
- "description": "generate, serve etc short urls over mongoose/mongodb/express",
- "version": "0.0.3",
+ "description": "Generate, retieve short urls over mongoose/mongodb/express",
+ "version": "0.0.4",
"repository": {
"type": "git",
"url": "git://github.com/edwardhotchkiss/short.git"

0 comments on commit e743e02

Please sign in to comment.