This repository has been archived by the owner on Apr 4, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathindex.js
65 lines (54 loc) · 1.44 KB
/
index.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
/**
* deps
*/
var slug = require('speakingurl');
/**
* slug plugin.
*
* Usage:
*
* mySchema.plugin(slug('title'));
*
* Options:
*
* - `.replace` characters to replace defaulted to `[^a-zA-Z]`
* - `.separator` separator to use, defaulted to `-`
* - `required` whether a slug is required, defaults to `true`
*
* @param {String} prop
* @param {Object} options
* @return {Function}
*/
module.exports = function(prop, opts){
return (function slugize(schema){
var title;
schema.add({
slug: {
type: 'String',
unique: (opts && opts.unique) ? true : false
}
});
if (opts && opts.track) {
schema.add({ slugs: [ String ] });
}
schema.pre('save', function(next){
var self = this;
if (prop && Array.isArray(prop)) {
var titles = [];
prop.forEach(function(el){
titles.push(self[el]);
});
title = titles.join(' ');
} else {
title = this[prop || 'title'];
}
var require = (opts && opts.required === false) ? false : true
, presets = (opts && opts.override) ? true : false;
if (require && !title) return next(new Error(prop + ' is required to create a slug'));
var mySlug = slug(title, opts);
if (opts && opts.track && self.slugs && self.slugs.indexOf( mySlug) == -1) self.slugs.push( mySlug );
if (title && !self.slug) self.slug = mySlug;
next();
});
});
};