Advertisement
Guest User

node.js url shortener

a guest
Oct 7th, 2010
1,454
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**********************
  2.  * ./init.js
  3.  **********************/
  4.  
  5. require('./Lib/MooTools').apply(GLOBAL);
  6.  
  7. var http  = require('http');
  8. http.ServerResponse.implement({
  9.     header : function (code, plain) {
  10.         this.writeHead(code, {
  11.             'Content-Type': plain ? 'text/plain' : 'text/html'
  12.         });
  13.     },
  14.     redirect : function (url, status) {
  15.         this.writeHead(status || 302, {
  16.             'Content-Type' : 'text/plain',
  17.             'Location'     : url
  18.         });
  19.         this.write('Redirecting to ' + url);
  20.         this.end();
  21.     }
  22. });
  23.  
  24. var conn = require('./Lib/mysql/mysql-libmysqlclient').createConnectionSync();
  25. conn.connectSync('localhost', 'NAME', 'PASS', 'nodejs');
  26.  
  27. var linkModel = new (require('./Link').Model)(conn);
  28. var renderer  = new (require('./Renderer').Renderer)(linkModel);
  29.  
  30. http.createServer(function (req, res) {
  31.     renderer.run(req, res);
  32. }).listen(8124, "127.0.0.1");
  33. console.log('Server running at http://127.0.0.1:8124/');
  34.  
  35. /**********************
  36.  * ./Link.js
  37.  **********************/
  38. require('./Lib/MooTools').apply(GLOBAL);
  39.  
  40. Link = new Class({
  41.     initialize : function (obj) {
  42.         this.setId(obj.id).id || this.setCode(obj.code);
  43.         this.setUrl(obj.url);
  44.     },
  45.     setId : function (id) {
  46.         this.id = (isNaN(id) || id <= 0) ? null : parseInt(id);
  47.         return this;
  48.     },
  49.     getId : function () {
  50.         return this.id;
  51.     },
  52.     setUrl : function (url) {
  53.         this.url = url || null;
  54.         return this;
  55.     },
  56.     getUrl : function () {
  57.         return this.url;
  58.     },
  59.     setCode : function (code) {
  60.         this.id = Link.fromCode(code);
  61.         return this;
  62.     },
  63.     getCode : function () {
  64.         return Link.getCode(this.id);
  65.     },
  66.  
  67. });
  68.  
  69. Link.getCode  = function (id) {
  70.     return id ? id.toString(36) : null;
  71. };
  72.  
  73. Link.fromCode = function (code) {
  74.     return code ? parseInt(code, 36) : null;
  75. };
  76.  
  77. Model = new Class({
  78.     conn : null,
  79.     initialize : function (conn) {
  80.         this.conn = conn;
  81.     },
  82.     create : function (args) {
  83.         return new Link(args);
  84.     },
  85.     get : function (link, fn) {
  86.         if (!link.getId()) throw 'EmptyId';
  87.  
  88.         var q = 'SELECT * FROM `shortLinks` WHERE `id` = ' + link.getId();
  89.  
  90.         this.conn.query(q, function (err, res) {
  91.             if (err) throw err;
  92.  
  93.             res.fetchAll(function (err, rows) {
  94.                 if (err) throw err;
  95.  
  96.                 fn(rows.length ? link.setUrl(rows[0].url) : null);
  97.  
  98.                 res.freeSync();
  99.             });
  100.         });
  101.     },
  102.     put : function (link, fn) {
  103.         var q = 'INSERT INTO `shortLinks` (`id`, `url`) ' +
  104.             'VALUES (NULL , "' + this.conn.escapeSync(link.getUrl()) + '");'
  105.  
  106.         this.conn.query(q, function (err, res) {
  107.             if (err) throw err;
  108.  
  109.             fn(link.setId(
  110.                 this.conn.lastInsertIdSync()
  111.             ));
  112.         }.bind(this));
  113.     }
  114. });
  115.  
  116. exports.Link  = Link;
  117. exports.Model = Model;
  118.  
  119. /**********************
  120.  * ./Renderer.js
  121.  **********************/
  122.  
  123. require('./Lib/MooTools').apply(GLOBAL);
  124.  
  125. var url = require('url');
  126. var fs  = require('fs');
  127.  
  128. exports.Renderer = new Class({
  129.     initialize : function (linkModel) {
  130.         this.link = linkModel;
  131.     },
  132.  
  133.     run : function (req, res) {
  134.         var path = url.parse(req.url, true);
  135.         if (path.query && 'add' in path.query) {
  136.             var addUrl = path.query.add;
  137.             if (!url.parse(addUrl).protocol) {
  138.                 addUrl = 'http://' + addUrl;
  139.             }
  140.             this.add(res, addUrl);
  141.         } else if (path.pathname.test(/^\/![0-9a-z]+$/)) {
  142.             this.send(res, path.pathname.substr(2));
  143.         } else {
  144.             this.index(res);
  145.         }
  146.     },
  147.  
  148.     add : function (res, url) {
  149.         res.header(200);
  150.         this.link.put(
  151.             this.link.create({ url : url }),
  152.             function (link) {
  153.                 res.end(link.getCode());
  154.             }
  155.         );
  156.     },
  157.     send : function (res, code) {
  158.         this.link.get(
  159.             this.link.create({ code : code }),
  160.             function (link) {
  161.                 if (link) {
  162.                     res.redirect(link.getUrl());
  163.                 } else {
  164.                     res.header(404, true);
  165.                     res.end('There is not such url');
  166.                 }
  167.             }
  168.         );
  169.     },
  170.     index : function (res) {
  171.         fs.readFile(__dirname + '/index.html', function (err, data) {
  172.             if (err) throw err;
  173.             res.header(200);
  174.             res.end(data);
  175.         })
  176.     }
  177. });
  178.  
  179. /**********************
  180.  * ./index.html
  181.  **********************/
  182. <!DOCTYPE html>
  183. <html>
  184.     <head>
  185.         <meta charset="UTF-8">
  186.         <title>Сокращатель ссылок на node.js</title>
  187.         <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
  188.         <script>
  189. $(function () {
  190.     $('input[type=submit]').click(function() {
  191.         var input = $('input[type=text]');
  192.         var url   = input.val();
  193.         input.val('');
  194.         url && $.ajax({
  195.             url : './',
  196.             data: ({ add : url }),
  197.             success : function (data) {
  198. var result = location.protocol + '//' + location.host + '/!' + data;
  199. $('#url')
  200.     .prepend(
  201.         $('<dd>').append(
  202.             $('<a>')
  203.                 .text(result)
  204.                 .attr('href', result)
  205.         )
  206.         .hide()
  207.         .fadeIn()
  208.     )
  209.     .prepend(
  210.         $('<dt>')
  211.             .text(url)
  212.             .hide()
  213.             .fadeIn()
  214.     );
  215.             }  // success function
  216.         }); // ajax object
  217.     }); // $('input[type=submit]').click
  218. }); // document.ready
  219.         </script>
  220.     </head>
  221.     <body>
  222.         <div id="form">
  223.             <input type="text"   />
  224.             <input type="submit" />
  225.         </div>
  226.         <dl id="url"></dl>
  227.     </body>
  228. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement