TwoToc code
[YouAndWeb_TwoToc] / server / api / show / show.controller.js
1 /**
2  * Using Rails-like standard naming convention for endpoints.
3  * GET     /api/shows              ->  index
4  * POST    /api/shows              ->  create
5  * GET     /api/shows/:id          ->  show
6  * PUT     /api/shows/:id          ->  update
7  * DELETE  /api/shows/:id          ->  destroy
8  */
9
10 'use strict';
11
12 var _ = require('lodash');
13 var Show = require('./show.model');
14 var User = require('../user/user.model');
15 // var Promise_ = require('promise');
16
17 function handleError(res, statusCode) {
18   statusCode = statusCode || 500;
19   return function(err) {
20     res.status(statusCode).send(err);
21   };
22 }
23
24 function responseWithResult(res, dig, statusCode) {
25   statusCode = statusCode || 200;
26   var promise = [];
27   return function(entity) {
28     if (entity) {
29       if (dig) {
30         entity.forEach(function(obj, index) {
31           promise.push(new Promise(function(resolve, reject) {
32             User.findById(obj.userId, function(err, userObj) {
33               obj.user = userObj;
34               resolve(obj);
35             });
36           }));
37         });
38         Promise.all(promise).then(function(data) {
39           // console.log(data);
40           res.status(statusCode).json(data);
41         });
42       } else {
43         User.findById(entity.userId, function(err, userObj) {
44           entity.user = userObj;
45           res.status(statusCode).json(entity);
46         });
47       }
48     }
49   };
50 }
51
52 function handleEntityNotFound(res) {
53   return function(entity) {
54     if (!entity) {
55       res.status(404).end();
56       return null;
57     }
58     return entity;
59   };
60 }
61
62 function saveUpdates(updates) {
63   return function(entity) {
64     var updated = _.merge(entity, updates);
65     return updated.saveAsync()
66       .spread(function(updated) {
67         return updated;
68       });
69   };
70 }
71
72 function removeEntity(res) {
73   return function(entity) {
74     if (entity) {
75       return entity.removeAsync()
76         .then(function() {
77           res.status(204).end();
78         });
79     }
80   };
81 }
82
83 // Gets a list of Shows
84 exports.index = function(req, res) {
85   var limit = req.query.limit;
86   var sq = {};
87   var date = req.query.date;
88   var category = req.query.category;
89   var fulltext = req.query.fulltext;
90   var lat = req.query.lat;
91   var lng = req.query.lng;
92   var maxDistance = 20; 
93   if (date) {
94     sq.date = {
95       $gte: date
96     }
97   }
98   if (category) {
99     sq.categoryId = category
100   }
101   if (lat && lng) {
102     sq.location = {
103       $near: [lng, lat],
104       $maxDistance: maxDistance
105     };
106   }
107   if (fulltext) {
108     var words = fulltext.replace(/[.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"").split(/\s+/);
109     var pattern = '';
110     for (let word of words) {
111       pattern += "(?=.*\\b" + word + "\\b)";
112     }
113     sq.title = new RegExp("^" + pattern + ".*$", 'i');
114   }
115   Show.find(sq).lean().limit(limit)
116     .then(responseWithResult(res, true))
117     .catch(handleError(res));
118 };
119
120
121 // Gets a single Show from the DB
122 exports.show = function(req, res) {
123   Show.findById(req.params.id).lean()
124     .then(handleEntityNotFound(res))
125     .then(responseWithResult(res))
126     .catch(handleError(res));
127 };
128
129 // Creates a new Show in the DB
130 exports.create = function(req, res) {
131   Show.createAsync(req.body)
132     .then(responseWithResult(res, 201))
133     .catch(handleError(res));
134 };
135
136 // Updates an existing Show in the DB
137 exports.update = function(req, res) {
138   if (req.body._id) {
139     delete req.body._id;
140   }
141   Show.findByIdAsync(req.params.id)
142     .then(handleEntityNotFound(res))
143     .then(saveUpdates(req.body))
144     .then(responseWithResult(res))
145     .catch(handleError(res));
146 };
147
148 // Deletes a Show from the DB
149 exports.destroy = function(req, res) {
150   Show.findByIdAsync(req.params.id)
151     .then(handleEntityNotFound(res))
152     .then(removeEntity(res))
153     .catch(handleError(res));
154 };