-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
50 lines (40 loc) · 1.07 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
const { nanoid, customAlphabet } = require('nanoid');
const DEFAULT_LENGTH = 12;
function generator(opts) {
return opts.alphabets ? customAlphabet(opts.alphabets, DEFAULT_LENGTH) : nanoid
}
function nanoidPlugin(schema, opts) {
if (schema.options._id !== undefined && schema.options._id === false) return;
if (typeof opts == 'number') {
opts = { length: opts }
}
opts.length = opts.length || DEFAULT_LENGTH;
let _id = '_id';
const dataObj = {};
dataObj[_id] = {
type: String,
default: function () {
return generator(opts)(opts.length);
}
};
schema.add(dataObj);
schema.pre('save', function (next) {
if (this.isNew && !this.constructor.$isArraySubdocument) {
attemptToGenerate(this, opts)
.then(function (newId) {
this[_id] = newId;
next()
})
.catch(next)
} else next();
});
}
function attemptToGenerate(doc, opts) {
const id = generator(opts)(opts.length);
return doc.constructor.exists({ _id: id })
.then(function (found) {
if (found) return attemptToGenerate(doc, opts.length);
return id
})
}
module.exports = nanoidPlugin;