-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdownload.js
More file actions
173 lines (144 loc) · 4.56 KB
/
download.js
File metadata and controls
173 lines (144 loc) · 4.56 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
var _ = require('underscore');
var async = require('async');
var baby = require('babyparse');
var keystone = require('../../');
var moment = require('moment');
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
exports = module.exports = function(req, res) {
var filters = req.list.processFilters(req.query.q);
var queryFilters = req.list.getSearchFilters(req.query.search, filters);
var relFields = [];
_.each(req.list.fields, function(field) {
if (field.type === 'relationship') {
relFields.push(field.path);
}
});
var getRowData = function getRowData(i) {
var rowData = { id: i.id };
if (req.list.get('autokey')) {
rowData[req.list.get('autokey').path] = i.get(req.list.get('autokey').path);
}
_.each(req.list.fields, function(field) {
if (field.type === 'boolean') {
rowData[field.path] = i.get(field.path) ? 'true' : 'false';
} else if (field.type === 'relationship') {
var refData = i.get(field.path);
if (field.many) {
var values = [];
if (Array.isArray(refData) && refData.length) {
_.forEach(refData, function(i) {
var name = field.refList.getDocumentName(i);
if(keystone.get('csv expanded')){
name = '[' + i.id + ',' + name + ']';
}
values.push(name);
});
}
rowData[field.path] = values.join(', ');
} else {
if (keystone.get('csv expanded')) {
rowData[field.path + '_id'] = refData ? refData.id : '';
rowData[field.path + '_name'] = refData ? field.refList.getDocumentName(refData) : field.format(i);
} else {
rowData[field.path] = refData ? field.refList.getDocumentName(refData) : field.format(i);
}
}
} else {
rowData[field.path] = field.format(i);
}
});
return rowData;
};
var query = req.list.model.find(queryFilters);
if (relFields) {
query.populate(relFields.join(' '));
}
query.exec(function(err, results) {
if (err) return res.status(500).json(err);
var sendCSV = function(data) {
res.attachment(req.list.path + '-' + moment().format('YYYYMMDD-HHMMSS') + '.csv');
res.setHeader('Content-Type', 'application/octet-stream');
var content = baby.unparse(data, {
delimiter: keystone.get('csv field delimiter') || ','
});
res.end(content, 'utf-8');
};
if (!results.length) {
// fast bail on no results
return sendCSV([]);
}
var data;
if (results[0].toCSV) {
/**
* Custom toCSV Method present
*
* Detect dependencies and call it. If the last dependency is `callback`, call it asynchronously.
*
* Support dependencies are:
* - req (current express request object)
* - user (currently authenticated user)
* - row (default row data, as generated without custom toCSV())
* - callback (invokes async mode, must be provided last)
*/
var deps = _.map(results[0].toCSV.toString().match(FN_ARGS)[1].split(','), function(i) { return i.trim(); });
var includeRowData = (deps.indexOf('row') > -1);
var map = {
req: req,
user: req.user
};
var applyDeps = function(fn, _this, _map) {
var args = _.map(deps, function(key) {
return _map[key];
});
return fn.apply(_this, args);
};
if (_.last(deps) === 'callback') {
// Allow async toCSV by detecting the last argument is callback
return async.map(results, function(i, callback) {
var _map = _.clone(map);
_map.callback = callback;
if (includeRowData) {
_map.row = getRowData(i);
}
applyDeps(i.toCSV, i, _map);
}, function(err, results) {
if (err) {
console.log('Error generating CSV for list ' + req.list.key);
console.log(err);
return res.send(keystone.wrapHTMLError('Error generating CSV', 'Please check the log for more details, or contact support.'));
}
sendCSV(results);
});
} else {
// Without a callback, toCSV must return the value
data = [];
if (includeRowData) {
// if row data is required, add it to the map for each iteration
_.each(results, function(i) {
var _map = _.clone(map);
_map.row = getRowData(i);
data.push(applyDeps(i.toCSV, i, _map));
});
} else {
// fast path: use the same map for each iteration
_.each(results, function(i) {
data.push(applyDeps(i.toCSV, i, map));
});
}
return sendCSV(data);
}
} else {
/**
* Generic conversion to CSV
*
* Loops through each of the fields in the List and uses each field's `format` method
* to generate the data
*/
data = [];
_.each(results, function(i) {
data.push(getRowData(i));
});
return sendCSV(data);
}
});
};