-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
77 lines (49 loc) · 1.61 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
67
68
69
70
71
72
73
74
75
76
77
'use strict';
/*
* Middleware per generazione di csv.
* ---------------------------------
*
* Intercetta una risposta json (quindi deve essere messo in fondo alla catena)
* se era stata richiesta come text/csv allora la trasforma in text/csv.
*
*/
var lodash = require('lodash');
var schemaTypes = {
mongoose: require('./lib/mongoose_schema')
};
function nullFormatter(){
return '';
}
function getPath(obj, path){
if(!obj){ return ''; }
for (var i=0; i<path.length; i++){
obj = obj[path[i]];
if(!obj){ return ''; }
}
return obj;
}
module.exports = function(model, schemaType, exclude, extend){
var exporter = schemaTypes[schemaType];
if(exporter === undefined){
throw new Error('Unrecognized schema type '+schemaType);
}
var cols = exporter.columns(model, exclude, extend);
return function(data){
//for each row
return data.reduce(function(rows, obj){
//for each columns
var row = cols.map(function(col, i){
//se è ricorsivo scendi
var toFormat= !!col.path ? getPath(obj, col.path) : obj[col.name];
//var toFormat = obj[col.name];
if(toFormat === null || toFormat === undefined){
//the value is passed, maybe in the future null and undefined will be treated differently
return nullFormatter(toFormat);
}
return cols[i].formatter(toFormat);
});
rows.push(row);
return rows;
}, [lodash.pluck(cols,'name')]);
};
};