forked from mimani/mongoose-diff-history
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiffHistory.js
220 lines (194 loc) · 6.67 KB
/
diffHistory.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
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
const omit = require('omit-deep');
const pick = require('lodash.pick');
const mongoose = require('mongoose');
// try to find an id property, otherwise just use the index in the array
const objectHash = (obj, idx) => obj._id || obj.id || `$$index: ${idx}`;
const diffPatcher = require('jsondiffpatch').create({ objectHash });
const History = require('./diffHistoryModel').model;
const isValidCb = cb => {
return cb && typeof cb === 'function';
};
const saveDiffObject = (currentObject, original, updated, opts, metaData) => {
const { __user: user, __reason: reason } = metaData || currentObject;
const diff = diffPatcher.diff(
JSON.parse(JSON.stringify(original)),
JSON.parse(JSON.stringify(updated))
);
if (opts.omit) {
omit(diff, opts.omit);
}
if (!diff || !Object.keys(diff).length) return;
const collectionId = currentObject._id;
const collectionName = currentObject.constructor.modelName;
return History.findOne({ collectionId, collectionName })
.sort('-version')
.then(lastHistory => {
const history = new History({
collectionId,
collectionName,
diff,
user,
reason,
version: lastHistory ? lastHistory.version + 1 : 0
});
return history.save();
});
};
const saveDiffHistory = (queryObject, currentObject, opts) => {
const updateParams = queryObject._update;
const dbObject = pick(currentObject, Object.keys(updateParams));
return saveDiffObject(currentObject, dbObject, updateParams, opts, queryObject.options);
};
const saveDiffs = (queryObject, opts) =>
queryObject
.find(queryObject._conditions)
.lean(false)
.cursor()
.eachAsync(result => saveDiffHistory(queryObject, result, opts));
const getVersion = (model, id, version, queryOpts, cb) => {
if (typeof queryOpts === 'function') {
cb = queryOpts;
queryOpts = undefined;
}
return model
.findById(id, null, queryOpts)
.then(latest => {
latest = latest || {};
return History.find(
{
collectionName: model.modelName,
collectionId: id,
version: { $gte: parseInt(version, 10) }
},
{ diff: 1, version: 1 },
{ sort: '-version' }
)
.lean()
.cursor()
.eachAsync(history => {
diffPatcher.unpatch(latest, history.diff);
})
.then(() => {
if (isValidCb(cb)) return cb(null, latest);
return latest;
});
})
.catch(err => {
if (isValidCb(cb)) return cb(err, null);
throw err;
});
};
const getDiffs = (modelName, id, opts, cb) => {
opts = opts || {};
if (typeof opts === 'function') {
cb = opts;
opts = {};
}
return History.find({ collectionName: modelName, collectionId: id }, null, opts)
.lean()
.then(histories => {
if (isValidCb(cb)) return cb(null, histories);
return histories;
})
.catch(err => {
if (isValidCb(cb)) return cb(err, null);
throw err;
});
};
const getHistories = (modelName, id, expandableFields, cb) => {
expandableFields = expandableFields || [];
if (typeof expandableFields === 'function') {
cb = expandableFields;
expandableFields = [];
}
const histories = [];
return History.find({ collectionName: modelName, collectionId: id })
.lean()
.cursor()
.eachAsync(history => {
const changedValues = [];
const changedFields = [];
for (const key in history.diff) {
if (history.diff.hasOwnProperty(key)) {
if (expandableFields.indexOf(key) > -1) {
const oldValue = history.diff[key][0];
const newValue = history.diff[key][1];
changedValues.push(key + ' from ' + oldValue + ' to ' + newValue);
} else {
changedFields.push(key);
}
}
}
const comment = 'modified ' + changedFields.concat(changedValues).join(', ');
histories.push({
changedBy: history.user,
changedAt: history.createdAt,
updatedAt: history.updatedAt,
reason: history.reason,
comment: comment
});
})
.then(() => {
if (isValidCb(cb)) return cb(null, histories);
return histories;
})
.catch(err => {
if (isValidCb(cb)) return cb(err, null);
throw err;
});
};
/**
* @param {Object} schema - Schema object passed by Mongoose Schema.plugin
* @param {Object} [opts] - Options passed by Mongoose Schema.plugin
* @param {string} [opts.uri] - URI for MongoDB (necessary, for instance, when not using mongoose.connect).
* @param {string|string[]} [opts.omit] - fields to omit from diffs (ex. ['a', 'b.c.d']).
*/
const plugin = function lastModifiedPlugin(schema, opts = {}) {
if (opts.uri) {
mongoose.connect(opts.uri).catch(e => {
console.error('mongoose-diff-history connection error:', e);
});
}
if (opts.omit && !Array.isArray(opts.omit)) {
if (typeof opts.omit === 'string') {
opts.omit = [opts.omit];
} else {
const errMsg = `opts.omit expects string or array, instead got '${typeof opts.omit}'`;
throw new TypeError(errMsg);
}
}
schema.pre('save', function (next) {
if (this.isNew) return next();
this.constructor
.findOne({ _id: this._id })
.then(original => saveDiffObject(this, original, this, opts))
.then(() => next())
.catch(next);
});
schema.pre('findOneAndUpdate', function (next) {
saveDiffs(this, opts)
.then(() => next())
.catch(next);
});
schema.pre('update', function (next) {
saveDiffs(this, opts)
.then(() => next())
.catch(next);
});
schema.pre('updateOne', function (next) {
saveDiffs(this, opts)
.then(() => next())
.catch(next);
});
schema.pre('remove', function (next) {
saveDiffObject(this, this, {}, opts)
.then(() => next())
.catch(next);
});
};
module.exports = {
plugin,
getVersion,
getDiffs,
getHistories
};