TwoToc code
[YouAndWeb_TwoToc] / server / api / show / show.controller.js
diff --git a/server/api/show/show.controller.js b/server/api/show/show.controller.js
new file mode 100755 (executable)
index 0000000..2a5c2d8
--- /dev/null
@@ -0,0 +1,154 @@
+/**
+ * Using Rails-like standard naming convention for endpoints.
+ * GET     /api/shows              ->  index
+ * POST    /api/shows              ->  create
+ * GET     /api/shows/:id          ->  show
+ * PUT     /api/shows/:id          ->  update
+ * DELETE  /api/shows/:id          ->  destroy
+ */
+
+'use strict';
+
+var _ = require('lodash');
+var Show = require('./show.model');
+var User = require('../user/user.model');
+// var Promise_ = require('promise');
+
+function handleError(res, statusCode) {
+  statusCode = statusCode || 500;
+  return function(err) {
+    res.status(statusCode).send(err);
+  };
+}
+
+function responseWithResult(res, dig, statusCode) {
+  statusCode = statusCode || 200;
+  var promise = [];
+  return function(entity) {
+    if (entity) {
+      if (dig) {
+        entity.forEach(function(obj, index) {
+          promise.push(new Promise(function(resolve, reject) {
+            User.findById(obj.userId, function(err, userObj) {
+              obj.user = userObj;
+              resolve(obj);
+            });
+          }));
+        });
+        Promise.all(promise).then(function(data) {
+          // console.log(data);
+          res.status(statusCode).json(data);
+        });
+      } else {
+        User.findById(entity.userId, function(err, userObj) {
+          entity.user = userObj;
+          res.status(statusCode).json(entity);
+        });
+      }
+    }
+  };
+}
+
+function handleEntityNotFound(res) {
+  return function(entity) {
+    if (!entity) {
+      res.status(404).end();
+      return null;
+    }
+    return entity;
+  };
+}
+
+function saveUpdates(updates) {
+  return function(entity) {
+    var updated = _.merge(entity, updates);
+    return updated.saveAsync()
+      .spread(function(updated) {
+        return updated;
+      });
+  };
+}
+
+function removeEntity(res) {
+  return function(entity) {
+    if (entity) {
+      return entity.removeAsync()
+        .then(function() {
+          res.status(204).end();
+        });
+    }
+  };
+}
+
+// Gets a list of Shows
+exports.index = function(req, res) {
+  var limit = req.query.limit;
+  var sq = {};
+  var date = req.query.date;
+  var category = req.query.category;
+  var fulltext = req.query.fulltext;
+  var lat = req.query.lat;
+  var lng = req.query.lng;
+  var maxDistance = 20; 
+  if (date) {
+    sq.date = {
+      $gte: date
+    }
+  }
+  if (category) {
+    sq.categoryId = category
+  }
+  if (lat && lng) {
+    sq.location = {
+      $near: [lng, lat],
+      $maxDistance: maxDistance
+    };
+  }
+  if (fulltext) {
+    var words = fulltext.replace(/[.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"").split(/\s+/);
+    var pattern = '';
+    for (let word of words) {
+      pattern += "(?=.*\\b" + word + "\\b)";
+    }
+    sq.title = new RegExp("^" + pattern + ".*$", 'i');
+  }
+  Show.find(sq).lean().limit(limit)
+    .then(responseWithResult(res, true))
+    .catch(handleError(res));
+};
+
+
+// Gets a single Show from the DB
+exports.show = function(req, res) {
+  Show.findById(req.params.id).lean()
+    .then(handleEntityNotFound(res))
+    .then(responseWithResult(res))
+    .catch(handleError(res));
+};
+
+// Creates a new Show in the DB
+exports.create = function(req, res) {
+  Show.createAsync(req.body)
+    .then(responseWithResult(res, 201))
+    .catch(handleError(res));
+};
+
+// Updates an existing Show in the DB
+exports.update = function(req, res) {
+  if (req.body._id) {
+    delete req.body._id;
+  }
+  Show.findByIdAsync(req.params.id)
+    .then(handleEntityNotFound(res))
+    .then(saveUpdates(req.body))
+    .then(responseWithResult(res))
+    .catch(handleError(res));
+};
+
+// Deletes a Show from the DB
+exports.destroy = function(req, res) {
+  Show.findByIdAsync(req.params.id)
+    .then(handleEntityNotFound(res))
+    .then(removeEntity(res))
+    .catch(handleError(res));
+};