-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathincrement.js
More file actions
291 lines (249 loc) · 8.28 KB
/
increment.js
File metadata and controls
291 lines (249 loc) · 8.28 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
'use strict';
/**
* Mongoose plugin
*/
const _ = require('lodash');
const Promise = require('bluebird');
const mongooseIncrement = function(mongoose) {
/**
* Setup counter schema and model
*
* @type {mongoose}
*/
const CounterSchema = new mongoose.Schema({
model: {
type: String,
require: true,
},
field: {
type: String,
require: true,
},
count: {
type: Number,
default: 0,
},
});
const Counter = mongoose.model('_Counter', CounterSchema);
/**
* Reset counter sequence start
*
* @param {Object} options Mongoose plugin options
* @return {Promise} Promise fulfilled when sequence has been reset
*/
function resetSequence(options) {
return Counter.findOneAndUpdate(
{ model: options.model, field: options.field },
{ count: options.start - options.increment },
{ new: true, upsert: true });
}
/**
* Calculate the current count
*
* @param {Object} options Counter options
* @param {Number} count current count increment
* @param {Object} resource Mongoose model instance
*
* @return {Number} new count
*/
function calculateCount(options, count, resource) {
let value = '';
if (_.isFunction(options.prefix)) {
value += options.prefix(resource);
}
else if (options.prefix) {
value += options.prefix.toString();
}
value += count;
if (options.hasVersion) {
value += `${options.delimiterVersion}${options.startVersion}${options.delimiterVersion}`;
}
if (_.isFunction(options.suffix)) {
value += options.suffix(resource);
}
else if (options.suffix) {
value += options.suffix.toString();
}
return value;
}
/**
* Retrieve the next sequence in the counter and update field
*
* @param {Object} options Counter options
* @param {Object} resource Mongoose model instance
* @param {Function} next Callback handler
*/
function nextCount(options, resource, next) {
if (!resource.isNew || !_.isUndefined(resource[options.field])) {
return next();
}
return Counter.findOne({
model: options.model,
field: options.field,
}).then((item) => {
let promise = Promise.resolve(item);
if (!item) {
promise = initCounter(options);
}
promise.then((counter) => {
counter.count += options.increment;
if (options.resetAfter > 0 && counter.count > options.resetAfter) {
counter.count = options.start;
}
resource[options.field] = calculateCount(options, counter.count, resource);
return counter.save(next);
});
}).catch(next);
}
/**
* Parse the sequence to get the prefix, counter and suffix
*
* @param {Object} options Counter options
*
* @return {Object} sequence parsed
*/
function parseSequence(options) {
const parsed = {
prefix: '',
counter: '',
suffix: '',
};
if (_.isFunction(options.prefix)) {
parsed.prefix = options.prefix(this);
}
else if (options.prefix) {
parsed.prefix = options.prefix.toString();
}
if (_.isFunction(options.suffix)) {
parsed.suffix = options.suffix(this);
}
else if (options.suffix) {
parsed.suffix = options.suffix.toString();
}
let counter = this[options.field];
if (_.isNumber(this[options.field])) {
counter = String(counter);
}
parsed.counter = counter.substring(parsed.prefix.length, counter.length - parsed.suffix.length);
if (_.isNumber(this[options.field])) {
parsed.counter = Number(parsed.counter);
}
if (options.hasVersion) {
const tab = parsed.counter.split(options.delimiterVersion);
parsed.counter = tab[0];
parsed.version = tab[1];
}
return parsed;
}
/**
* Retrieve the next sequence in the counter and update field
*
* @param {Object} options Counter options
* @return {Promise} Promise fulfilled when increment field has been setted
*/
function nextSequence(options) {
const resource = this;
return new Promise((resolve, reject) => {
nextCount(options, resource, (err) =>
(err ? reject(err) : resolve())
);
});
}
/**
* Set the next version from the current document version
*
* @param {Object} options Counter options
* @return {Number} new version counter
*/
function nextVersion(options) {
const opts = _.cloneDeep(options);
const parsedSequence = this.parseSequence(options);
opts.startVersion = Number(parsedSequence.version) + 1;
this[options.field] = calculateCount(opts, parsedSequence.counter, this);
return this[options.field];
}
/**
* Create a new counter for the current model
*
* @param {Object} options Counter options
* @return {Object} counter mongoose doc
*/
function initCounter(options) {
const newCount = new Counter({
model: options.model,
field: options.field,
count: options.start - options.increment,
});
return newCount.save();
}
/**
* Mongoose plugin, adds a counter for a given `model` and `field`, also add
* the autoincrement field into the schema.
*
* @param {Object} schema Mongoose schema
* @param {Options} options Additional options for autoincremented field
* @property {String} modelName mongoose model name
* @property {String} fieldName mongoose increment field name
* @property {Integer} [start] start number for counter, default `1`
* @property {Integer} [increment] number to increment counter, default `1`
* @property {String/Function} [prefix] counter prefix, default ``
* @property {String/Function} [suffix] counter suffix, default ``
* @property {Boolean} [unique] unique field, default `true`
* @property {Integer} [resetAfter] reset counter, default `0`
* @property {Boolean} [hasVersion] has version, default `false`
* @property {Integer} [startVersion] start number for version, default `1`
* @property {String} [delimiterVersion] delimiter for version counter, default `-`
*/
return function plugin(schema, options) {
if (!_.isPlainObject(options)) {
throw new Error('Mongoose Increment Plugin: require `options` parameter');
}
if (!_.isString(options.modelName)) {
throw new Error('Mongoose Increment Plugin: require `options.modelName` parameter');
}
if (!_.isString(options.fieldName)) {
throw new Error('Mongoose Increment Plugin: require `options.fieldName` parameter');
}
if (options.start && !_.isInteger(options.start)) {
throw new Error('Mongoose Increment Plugin: require `options.start` parameter must be an integer');
}
if (options.increment && !_.isInteger(options.increment)) {
throw new Error('Mongoose Increment Plugin: require `options.increment` parameter must be an integer');
}
if (options.startVersion && !_.isInteger(options.startVersion)) {
throw new Error('Mongoose Increment Plugin: require `options.startVersion` parameter must be an integer');
}
const opts = {
model: options.modelName,
field: options.fieldName,
start: options.start || 1,
increment: options.increment || 1,
prefix: options.prefix || '',
suffix: options.suffix || '',
type: options.type || Number,
unique: options.unique,
resetAfter: options.resetAfter || 0,
hasVersion: options.hasVersion || false,
startVersion: options.startVersion || 1,
delimiterVersion: options.delimiterVersion || '-',
};
if (opts.unique !== false) opts.unique = true;
const fieldSchema = {};
fieldSchema[opts.field] = {
type: opts.type,
require: true,
unique: opts.unique,
};
schema.add(fieldSchema);
schema.methods.nextSequence = _.partial(nextSequence, opts);
schema.methods.parseSequence = _.partial(parseSequence, opts);
if (opts.hasVersion) {
schema.methods.nextVersion = _.partial(nextVersion, opts);
}
schema.statics.resetSequence = _.partial(resetSequence, opts);
schema.pre('save', function preSave(next) {
nextCount(opts, this, next);
});
}
}
module.exports = mongooseIncrement;