-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmongoose-title-case.js
80 lines (63 loc) · 1.76 KB
/
mongoose-title-case.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
/*
Mongoose Title Case
*/
const SURNAME_PREFIX_DICT = [
'mc',
'mac',
'fitz'
];
function titleize (str, options = {}) {
let expression = options.prefixes ?
new RegExp('^.| .|\'.|-.|' + options.prefixes.map(p => `(?<=${p}).`).join('|'), 'gi') :
/^.| .|'.|-./g;
return str.toLowerCase().replace(expression, match => match.toUpperCase());
}
/**
* Title Case Plugin Signature
* @identity
*
* @param {Object} schema Mongoose Schema
* @param {Object} options Options Hash
* @return {Object} Mongoose Schema
*/
function MongooseTitleCase (schema, options) {
if (!options.paths) {
throw new Error('Mongoose Title Case requires "paths" to be specified in the options hash');
}
var paths = options.paths;
schema.pre('save', function (next) {
var doc = this;
var parse = previous => {
paths.forEach(path => {
var _path = path ? typeof path === 'string' ? path : path.path : path;
var raw = this.get(_path),
previousValue = previous ? previous.get(_path) : false;
if (!raw || !!previousValue && previousValue === raw) {
return;
}
const titleizeArgs = [ raw ];
if (path.surname) {
titleizeArgs.push({
prefixes: options.surnamePrefixes || SURNAME_PREFIX_DICT
});
}
var updateValue = titleize.apply(null, titleizeArgs);
if (path.trim !== false && options.trim !== false) {
updateValue = updateValue.trim();
}
this.set(_path, updateValue);
});
next();
};
if (this.isNew) {
parse();
} else {
doc.constructor.findById(this._id)
.exec()
.then(parse)
.catch(next);
}
});
return schema;
}
module.exports = MongooseTitleCase;