Skip to content

feat (mongoose): use mongoose-bird to promisify the mongoose API #503

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion app/templates/_package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
"lodash": "~2.4.1",<% if(filters.jade) { %>
"jade": "~1.2.0",<% } %><% if(filters.html) { %>
"ejs": "~0.8.4",<% } %><% if(filters.mongoose) { %>
"mongoose": "~3.8.8",<% } %><% if(filters.auth) { %>
"mongoose": "~3.8.8",
"mongoose-bird": "~0.0.1",
<% } %><% if(filters.auth) { %>
"jsonwebtoken": "^0.3.0",
"express-jwt": "^0.1.3",
"passport": "~0.2.0",
Expand Down
123 changes: 84 additions & 39 deletions app/templates/server/api/thing/thing.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,62 @@

'use strict';

var _ = require('lodash');<% if (filters.mongoose) { %>
var Thing = require('./thing.model');<% } %>
<% if (filters.mongoose) { %>
var _ = require('lodash');
var Thing = require('./thing.model');

function handleError(res, statusCode){
statusCode = statusCode || 500;
return function(err){
res.send(statusCode, err);
};
}

function responseWithResult(res, statusCode){
statusCode = statusCode || 200;
return function(entity){
if(entity){
return res.json(statusCode, entity);
}
};
}

function handleEntityNotFound(res){
return function(entity){
if(!entity){
res.send(404);
return null;
}
return entity;
};
}

function saveUpdates(updates){
return function(entity){
var updated = _.merge(entity, updates);
return updated
.saveAsync()
.then(function () {
return updated;
});
};
}

function removeEntity(res){
return function (entity) {
if(entity){
return entity.removeAsync()
.then(function() {
return res.send(204);
});
}
};
}
<% } %>

// Get list of things
exports.index = function(req, res) {<% if (!filters.mongoose) { %>
exports.index = function(req, res) {
<% if (!filters.mongoose) { %>
res.json([
{
name : 'Development Tools',
Expand All @@ -34,56 +85,50 @@ exports.index = function(req, res) {<% if (!filters.mongoose) { %>
name : 'Deployment Ready',
info : 'Easily deploy your app to Heroku or Openshift with the heroku and openshift subgenerators'
}
]);<% } %><% if (filters.mongoose) { %>
Thing.find(function (err, things) {
if(err) { return handleError(res, err); }
return res.json(200, things);
});<% } %>
};<% if (filters.mongoose) { %>
]);
<% } %>
<% if (filters.mongoose) { %>
Thing.findAsync()
.then(responseWithResult(res))
.catch(handleError(res));
<% } %>
};

<% if (filters.mongoose) { %>

// Get a single thing
exports.show = function(req, res) {
Thing.findById(req.params.id, function (err, thing) {
if(err) { return handleError(res, err); }
if(!thing) { return res.send(404); }
return res.json(thing);
});
Thing.findByIdAsync(req.params.id)
.then(handleEntityNotFound(res))
.then(responseWithResult(res))
.catch(handleError(res));
};

// Creates a new thing in the DB.
exports.create = function(req, res) {
Thing.create(req.body, function(err, thing) {
if(err) { return handleError(res, err); }
return res.json(201, thing);
});
Thing.createAsync(req.body)
.then(responseWithResult(res, 201))
.catch(handleError(res));
};

// Updates an existing thing in the DB.
exports.update = function(req, res) {
if(req.body._id) { delete req.body._id; }
Thing.findById(req.params.id, function (err, thing) {
if (err) { return handleError(res, err); }
if(!thing) { return res.send(404); }
var updated = _.merge(thing, req.body);
updated.save(function (err) {
if (err) { return handleError(res, err); }
return res.json(200, thing);
});
});
if(req.body._id) {
delete req.body._id;
}
Thing.findByIdAsync(req.params.id)
.then(handleEntityNotFound(res))
.then(saveUpdates(req.body))
.then(responseWithResult(res))
.catch(handleError(res));
};

// Deletes a thing from the DB.
exports.destroy = function(req, res) {
Thing.findById(req.params.id, function (err, thing) {
if(err) { return handleError(res, err); }
if(!thing) { return res.send(404); }
thing.remove(function(err) {
if(err) { return handleError(res, err); }
return res.send(204);
});
});
Thing.findByIdAsync(req.params.id)
.then(handleEntityNotFound(res))
.then(removeEntity(res))
.catch(handleError(res));
};

function handleError(res, err) {
return res.send(500, err);
}<% } %>
<% } %>
2 changes: 1 addition & 1 deletion app/templates/server/api/thing/thing.model(mongoose).js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

var mongoose = require('mongoose'),
var mongoose = require('mongoose-bird')(),
Schema = mongoose.Schema;

var ThingSchema = new Schema({
Expand Down
111 changes: 71 additions & 40 deletions app/templates/server/api/user(auth)/user.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,37 @@ var passport = require('passport');
var config = require('../../config/environment');
var jwt = require('jsonwebtoken');

var validationError = function(res, err) {
return res.json(422, err);
var validationError = function(res, statusCode) {
statusCode = statusCode || 422;
return function(err){
res.json(statusCode, err);
};
};

function handleError(res, statusCode){
statusCode = statusCode || 500;
return function(err){
res.send(statusCode, err);
};
}

function respondWith(res, statusCode){
statusCode = statusCode || 200;
return function(){
res.send(statusCode);
};
}

/**
* Get list of users
* restriction: 'admin'
*/
exports.index = function(req, res) {
User.find({}, '-salt -password', function (err, users) {
if(err) return res.send(500, err);
res.json(200, users);
});
User.findAsync({}, '-salt -password')
.then(function (users) {
res.json(200, users);
})
.catch(handleError(res));
};

/**
Expand All @@ -27,11 +45,12 @@ exports.create = function (req, res, next) {
var newUser = new User(req.body);
newUser.provider = 'local';
newUser.role = 'user';
newUser.save(function(err, user) {
if (err) return validationError(res, err);
var token = jwt.sign({_id: user._id }, config.secrets.session, { expiresInMinutes: 60*5 });
res.json({ token: token });
});
newUser.saveAsync()
.then(function(user) {
var token = jwt.sign({_id: user._id }, config.secrets.session, { expiresInMinutes: 60*5 });
res.json({ token: token });
})
.catch(validationError(res));
};

/**
Expand All @@ -40,22 +59,26 @@ exports.create = function (req, res, next) {
exports.show = function (req, res, next) {
var userId = req.params.id;

User.findById(userId, function (err, user) {
if (err) return next(err);
if (!user) return res.send(401);
res.json(user.profile);
});
User.findByIdAsync(userId)
.then(function (user) {
if(!user) {
return res.send(401);
}
res.json(user.profile);
})
.catch(function(err){
return next(err);
});
};

/**
* Deletes a user
* restriction: 'admin'
*/
exports.destroy = function(req, res) {
User.findByIdAndRemove(req.params.id, function(err, user) {
if(err) return res.send(500, err);
return res.send(204);
});
User.findByIdAndRemoveAsync(req.params.id)
.then(respondWith(res, 204))
.catch(handleError(res));
};

/**
Expand All @@ -66,35 +89,43 @@ exports.changePassword = function(req, res, next) {
var oldPass = String(req.body.oldPassword);
var newPass = String(req.body.newPassword);

User.findById(userId, function (err, user) {
user.authenticate(oldPass, function(authErr, authenticated) {
if (authErr) res.send(403);
User.findByIdAsync(userId)
.then(function(user) {
user.authenticate(oldPass, function(authErr, authenticated) {
if (authErr) res.send(403);

if (authenticated) {
user.password = newPass;
user.save(function(err) {
if (err) return validationError(res, err);
res.send(200);
});
} else {
res.send(403);
}
if (authenticated) {
user.password = newPass;
user.saveAsync()
.then(respondWith(res, 200))
.catch(validationError(res));
} else {
res.send(403);
}
});
})
.catch(function(authErr){
res.send(403);
});
});
};

/**
* Get my info
*/
exports.me = function(req, res, next) {
var userId = req.user._id;
User.findOne({
_id: userId
}, '-salt -password', function(err, user) { // don't ever give out the password or salt
if (err) return next(err);
if (!user) return res.json(401);
res.json(user);
});

User.findOneAsync({ _id: userId }, '-salt -password')
.then(function(user) { // don't ever give out the password or salt
if (!user) {
return res.json(401);
}
res.json(user);
})
.catch(function(err){
return next(err);
});

};

/**
Expand Down
27 changes: 17 additions & 10 deletions app/templates/server/api/user(auth)/user.model.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

var mongoose = require('mongoose');
var mongoose = require('mongoose-bird')();
var Schema = mongoose.Schema;
var crypto = require('crypto');<% if(filters.oauth) { %>
var authTypes = ['github', 'twitter', 'facebook', 'google'];<% } %>
Expand Down Expand Up @@ -53,7 +53,9 @@ UserSchema
UserSchema
.path('email')
.validate(function(email) {<% if (filters.oauth) { %>
if (authTypes.indexOf(this.provider) !== -1) return true;<% } %>
if (authTypes.indexOf(this.provider) !== -1){
return true;
} <% } %>
return email.length;
}, 'Email cannot be blank');

Expand All @@ -70,14 +72,19 @@ UserSchema
.path('email')
.validate(function(value, respond) {
var self = this;
this.constructor.findOne({email: value}, function(err, user) {
if(err) throw err;
if(user) {
if(self.id === user.id) return respond(true);
return respond(false);
}
respond(true);
});
return this.constructor.findOneAsync({email: value})
.then(function(user) {
if(user) {
if(self.id === user.id) {
return respond(true);
}
return respond(false);
}
return respond(true);
})
.catch(function(err){
throw err;
});
}, 'The specified email address is already in use.');

var validatePresenceOf = function(value) {
Expand Down
Loading