/*
 * POST create a route
 */

var db = require('../db')

var mongo = db.mongo;
var mongo_db = db.mongo_db;

exports.create = function(req, res) {
  var name = req.params.name;
  mongo.open(function(err, client) {
    var db = client.db(mongo_db);
    db.collection('endpoints').count({ name: name }, function(err, found){
      if (!found) {
        var password = req.body.password;
        db.collection('endpoints').insert({
          name: name,
          password: password, // TODO hash+salt
          contents: '#!/bin/sh\ntouch /tmp/cheshire'
        }, function(err, result) {
          res.send('200', 'Endpoint successfully created.');
        });
      } else {
        res.send(400, 'endpoint already exists'); // TODO is 400 the right response?
      }
      client.close();
    });
  });
};

exports.read = function(req, res) {
  var name = req.params.name;
  mongo.open(function(err, client) {
    var db = client.db(mongo_db);
    db.collection('endpoints').findOne({ name: name }, function(err, result){
      if (result) {
        res.send(200, result.contents);
      } else {
        res.send(404, 'echo Endpoint ' + name + ' not found');
      }
      client.close();
    });
  });
};

exports.update = function(req, res) {
  var name = req.params.name;
  var password = req.body.password;
  var contents = req.body.contents;
  mongo.open(function(err, client) {
    var db = client.db(mongo_db);
    db.collection('endpoints').findOne({ name: name }, function(err, result){
      if (result.password != password) {
        client.close();
        res.send(403, 'Incorrect password for endpoint');
      } else {
        db.collection('endpoints').update(
          { name: name },
          { $set: { contents: contents } },
          function(err, result){
            client.close();
            res.send(200, 'okay');
        });
      }
    });
  });
}

@@ -572,32 +572,58 @@
 (err, result) %7B%0A
+          client.close();%0A
           res.se
@@ -663,24 +663,24 @@
 created.');%0A
-
         %7D);%0A
@@ -686,32 +686,56 @@
 %0A      %7D else %7B%0A
+        client.close();%0A
         res.send
@@ -811,38 +811,16 @@
       %7D%0A
-      client.close();%0A
     %7D);%0A
@@ -1076,37 +1076,255 @@
     
-res.send(200, result.contents
+var contents = result.contents;%0A        db.collection('endpoints').update(%7B%0A          name: name%0A        %7D, %7B%0A          $set: %7B contents: '' %7D%0A        %7D,function(err, result) %7B%0A          res.send(200, contents);%0A          client.close();%0A        %7D
 );%0A 
@@ -1398,30 +1398,24 @@
  found');%0A  
-    %7D%0A
       client
@@ -1420,24 +1420,32 @@
 nt.close();%0A
+      %7D%0A
     %7D);%0A  %7D)

Remove script after it is GETed once