forked from strongloop/loopback
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheckpoint.js
63 lines (56 loc) · 1.5 KB
/
checkpoint.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
/**
* Module Dependencies.
*/
var assert = require('assert');
/**
* Checkpoint list entry.
*
* @property id {Number} the sequencial identifier of a checkpoint
* @property time {Number} the time when the checkpoint was created
* @property sourceId {String} the source identifier
*
* @class Checkpoint
* @inherits {PersistedModel}
*/
module.exports = function(Checkpoint) {
// Workaround for https://github.com/strongloop/loopback/issues/292
Checkpoint.definition.rawProperties.time.default =
Checkpoint.definition.properties.time.default = function() {
return new Date();
};
/**
* Get the current checkpoint id
* @callback {Function} callback
* @param {Error} err
* @param {Number} checkpointId The current checkpoint id
*/
Checkpoint.current = function(cb) {
var Checkpoint = this;
this.find({
limit: 1,
order: 'seq DESC'
}, function(err, checkpoints) {
if (err) return cb(err);
var checkpoint = checkpoints[0];
if (checkpoint) {
cb(null, checkpoint.seq);
} else {
Checkpoint.create({seq: 0}, function(err, checkpoint) {
if (err) return cb(err);
cb(null, checkpoint.seq);
});
}
});
};
Checkpoint.beforeSave = function(next, model) {
if (!model.getId() && model.seq === undefined) {
model.constructor.current(function(err, seq) {
if (err) return next(err);
model.seq = seq + 1;
next();
});
} else {
next();
}
};
};