-
Notifications
You must be signed in to change notification settings - Fork 73k
Expand file tree
/
Copy pathprofile.js
More file actions
111 lines (92 loc) · 2.61 KB
/
profile.js
File metadata and controls
111 lines (92 loc) · 2.61 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
'use strict';
var find_options = require('./query');
var consts = require('../constants');
function storage (collection, ctx) {
var ObjectID = require('mongodb-legacy').ObjectId;
function create (obj, fn) {
obj.created_at = (new Date( )).toISOString( );
api().insertOne(obj, function (err, doc) {
if (err) {
console.log("Error saving profile data", obj, err, doc);
fn(err);
return;
}
fn(err, obj);
});
ctx.bus.emit('data-received');
}
function save (obj, fn) {
try {
obj._id = new ObjectID(obj._id);
} catch (err) {
obj._id = new ObjectID();
}
if (!Object.prototype.hasOwnProperty.call(obj, 'created_at')) {
obj.created_at = (new Date( )).toISOString( );
}
// Match existing profiles by _id only. The profile editor rewrites created_at on save.
api().replaceOne({ _id: obj._id }, obj, { upsert: true }, function (err) {
//id should be added for new docs
fn(err, obj);
});
ctx.bus.emit('data-received');
}
function list (fn, count) {
const limit = count !== null ? count : Number(consts.PROFILES_DEFAULT_COUNT);
return api( ).find({ }).limit(limit).sort({startDate: -1}).toArray(fn);
}
function list_query (opts, fn) {
storage.queryOpts = {
walker: {}
, dateField: 'startDate'
};
function limit () {
if (opts && opts.count) {
return this.limit(parseInt(opts.count));
}
return this;
}
return limit.call(api()
.find(query_for(opts))
.sort(opts && opts.sort && query_sort(opts) || { startDate: -1 }), opts)
.toArray(fn);
}
function query_for (opts) {
var retVal = find_options(opts, storage.queryOpts);
return retVal;
}
function query_sort (opts) {
if (opts && opts.sort) {
var sortKeys = Object.keys(opts.sort);
for (var i = 0; i < sortKeys.length; i++) {
if (opts.sort[sortKeys[i]] == '1') {
opts.sort[sortKeys[i]] = 1;
}
else {
opts.sort[sortKeys[i]] = -1;
}
}
return opts.sort;
}
}
function last (fn) {
return api().find().sort({startDate: -1}).limit(1).toArray(fn);
}
function remove (_id, fn) {
var objId = new ObjectID(_id);
api( ).deleteOne({ '_id': objId }, fn);
ctx.bus.emit('data-received');
}
function api () {
return ctx.store.collection(collection);
}
api.list = list;
api.list_query = list_query;
api.create = create;
api.save = save;
api.remove = remove;
api.last = last;
api.indexedFields = ['startDate'];
return api;
}
module.exports = storage;