-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
66 lines (56 loc) · 1.71 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
66
const mongoose = require('mongoose');
const moment = require('moment-timezone');
const get = require('lodash.get');
const set = require('lodash.set');
const findPaths = (schema, options) => {
const SchemaDate = mongoose.Schema.Types.Date;
return Object.keys(schema.paths).filter((path) => {
if (options.paths.length) return options.paths.indexOf(path) !== -1;
return schema.paths[path] instanceof SchemaDate;
});
};
/**
*
* @param {Object} schema
* @param {Object} options Options object
* @param {String[]} options.paths Schema paths
*/
module.exports = function timeZone(schema, options = {}) {
options = Object.assign(options, {
paths: [],
});
const paths = findPaths(schema, options);
const offset = moment().utcOffset() * 60 * 1000;
function fixOffset(doc, add) {
paths.forEach((path) => {
const date = get(doc, path);
if (date) {
const modifier = add ? 1 : -1;
const fixedOffset = date.valueOf() + (modifier * offset);
set(doc, path, new Date(fixedOffset));
}
});
}
function addOffset(next) {
if (!this) return next();
fixOffset(this, true);
next();
}
function subtractOffset(docs, next) {
const documents = [];
if (!docs) return next();
if (!Array.isArray(docs)) {
documents.push((docs.constructor.name === 'model') ? docs : this);
} else {
documents.push(...docs);
}
documents.forEach(result => fixOffset(result, false));
next();
}
schema.pre('save', addOffset);
schema.pre('findOneAndUpdate', addOffset);
schema.post('save', subtractOffset);
schema.post('find', subtractOffset);
schema.post('findOne', subtractOffset);
schema.post('findOneAndUpdate', subtractOffset);
};