Return to Snippet

Revision: 63716
at June 1, 2013 04:54 by redhatmatt


Initial Code
var express = require('express'),
    app     = express(),
    redis   = require('redis'),
    client  = redis.createClient(),
    QRCode  = require('qrcode');
 
app.use(express.bodyParser());
 
app.post('/new', function(req, res){
  if(req.body.url){
    var url_id = new Buffer(req.body.url).toString('base64');
    client.keys(url_id,function(err,keys) {
      if (err) res.send({'message':'Internal Server Error'},500);
      if (keys.length != 0){
        res.send({'message':'Conflict','keys':keys},409);
      }
      else {
        client.set(url_id, req.body.url,function(err,status){
          if (err) res.send({'message':'Internal Server Error'},500);
          else {
           
            QRCode.toDataURL('http://localhost:3000/go/'+url_id,function(err,dataURL){
              var response = {
                    qrcode : dataURL
                  };
                  response[url_id] = req.body.url;
              res.send(response,200)
            });
           
          };
        });
       
      }
    });
   
  }
  else {
    res.send(400)
  }
});
 
app.get('/go/:hash',function(req,res){
  if(req.params.hash){
    client.exists(req.params.hash, function (err, doesExist) {
      if (doesExist == false) {
        res.send({'message':'Not Found'},404);
      };
      if (doesExist == true) {
        client.get(req.params.hash,function(err,url) {
          if (err) res.send({'message':'Internal Server Error'},500);
          else {
            res.redirect(url.toString(), 301);
          }
        })
      }
    });
  }
  else{
    res.send(404)
  }
});
 
app.listen(3000);
console.log('Listening on port 3000');

Initial URL


Initial Description
It currently uses redis as a store for the data. The url's are pretty long since it's all base64 encoded data and the images are returned as base64 encoded PNG's but that can be solved pretty easily. This could be used a service for something kind of authentication front end, drupal

Initial Title
node.js_url_shortener_w_qr_code_generation_api/service by Matt Grill

Initial Tags
javascript, api, service

Initial Language
JavaScript