This repository has been archived by the owner on Jan 14, 2020. It is now read-only.
/
badge.js
91 lines (83 loc) · 1.8 KB
/
badge.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
var db = require('./');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var util = require('../lib/util');
var maxLength = function (field, length) {
function lengthValidator() {
if (!this[field]) return true;
return this[field].length <= length;
}
var msg = 'maxLength';
return [lengthValidator, msg];
}
var BehaviorSchema = new Schema({
shortname: {
type: String,
trim: true,
required: true
},
count: {
type: Number,
min: 0,
required: true
}
});
var BadgeSchema = new Schema({
shortname: {
type: String,
trim: true,
required: true,
unique: true
},
name: {
type: String,
trim: true,
required: true,
unique: true,
validate: maxLength('name', 128)
},
description: {
type: String,
trim: true,
required: true,
validate: maxLength('description', 128)
},
criteria: {
content: {
type: String,
trim: true
},
url: {
type: String,
trim: true
}
},
behaviors: {
type: [BehaviorSchema],
unique: true
},
prerequisites: {
type: [String]
}
});
var Badge = db.model('Badge', BadgeSchema);
function setShortnameDefault(next) {
if (!this.shortname && this.name)
this.shortname = util.slugify(this.name);
next();
}
BadgeSchema.pre('validate', setShortnameDefault);
Badge.findByBehavior = function findByBehavior(shortname, callback) {
var searchTerms = { behaviors: { '$elemMatch': { shortname: shortname }}};
return Badge.find(searchTerms, callback);
};
Badge.prototype.removeBehavior = function removeBehavior(shortname) {
var behaviors = this.behaviors.filter(function (behavior) {
if (behavior.shortname === shortname)
return null;
return behavior;
});
this.behaviors = behaviors;
return this;
};
module.exports = Badge;