Skip to content
This repository has been archived by the owner on Jan 14, 2020. It is now read-only.

Commit

Permalink
BadgeInstance method for checking if a user has a badge.
Browse files Browse the repository at this point in the history
  • Loading branch information
brianloveswords committed Oct 16, 2012
1 parent 0079d61 commit d93637e
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 5 deletions.
32 changes: 30 additions & 2 deletions models/badge-instance.js
Expand Up @@ -13,7 +13,6 @@ var BadgeInstanceSchema = new Schema({
type: String,
required: true,
trim: true,
unique: true,
match: regex.email
},
badge: {
Expand All @@ -34,7 +33,12 @@ var BadgeInstanceSchema = new Schema({
hash: {
type: String,
required: true,
}
},
userBadgeKey: {
type: String,
required: true,
unique: true
},
});
var BadgeInstance = db.model('BadgeInstance', BadgeInstanceSchema);

Expand Down Expand Up @@ -70,4 +74,28 @@ BadgeInstanceSchema.pre('validate', function hashDefault(next) {
next();
});

/**
* Set the `userBadgeKey` field to be the concatenation of the `user`
* and `badge` fields.
*/
BadgeInstanceSchema.pre('validate', function userBadgeKeyDefault(next) {
if (this.userBadgeKey) return next();
this.userBadgeKey = this.user + '.' + this.badge;
next();
});

/**
* Check whether a user has a badge.
*
* @param {String} user Email address for user
* @param {String} shortname The badge shortname
*/

BadgeInstance.userHasBadge = function userHasBadge(user, shortname, callback) {
var query = { userBadgeKey: user + '.' + shortname };
BadgeInstance.findOne(query, { user: 1 }, function (err, instance) {
if (err) return callback(err);
return callback(null, !!instance);
});
};
module.exports = BadgeInstance;
22 changes: 19 additions & 3 deletions test/badge-instance-model.test.js
Expand Up @@ -19,13 +19,13 @@ test.applyFixtures({
behaviors: [{ shortname: 'link', count: 5 }]
}),
'dummy-instance': new BadgeInstance({
user: 'dummy@example.org',
user: 'brian@example.org',
hash: 'hash',
badge: 'link-basic',
badge: 'link-advanced',
assertion: '{ "assertion" : "yep" }',
seen: true
}),
}, function () {
}, function (fixtures) {
test('BadgeInstance#save: test defaults', function (t) {
var instance = new BadgeInstance({
user: 'brian@example.org',
Expand All @@ -40,6 +40,22 @@ test.applyFixtures({
})
});

test('BadgeInstance#userHasBadge', function (t) {
var instance = fixtures['dummy-instance'];
var user = instance.user;
var badge = instance.badge;
BadgeInstance.userHasBadge(user, badge, function (err, hasBadge) {
t.notOk(err, 'should not have an error');
t.same(hasBadge, true, 'user should have badge');

BadgeInstance.userHasBadge(user, 'non-existent', function (err, hasBadge) {
t.notOk(err, 'should not have an error');
t.same(hasBadge, false, 'user should have badge');
t.end();
});
});
});

// necessary to stop the test runner
test('shutting down #', function (t) {
db.close(); t.end();
Expand Down

0 comments on commit d93637e

Please sign in to comment.