This repository has been archived by the owner on Nov 23, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
89 lines (78 loc) · 2.42 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
78
79
80
81
82
83
84
85
86
87
88
89
var http = require('http'),
async = require('async'),
template = require('string-template'),
filtrex = require('filtrex'),
DATA_URL_TEMPLATE = 'http://pooleapp.com/data/{secret}.json';
function filterSessions(filterExpr, struct) {
if ( !filterExpr ) {
return struct;
}
struct.sessions = struct.sessions.filter(
filtrex(filterExpr)
);
return struct;
}
function fetchFormData(formName, formInfo, cb) {
http.get(template(DATA_URL_TEMPLATE, formInfo), function (res) {
var struct, body = '';
if ( res.statusCode >= 400 ) {
cb("PooleApp server answered with a " + res.statusCode);
return;
}
res.setEncoding('utf8');
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function () {
try {
struct = filterSessions(formInfo.filter, JSON.parse(body));
} catch(e) {
return cb(e);
}
cb(false, {
"formName": formName,
"identifier": formInfo.identifier,
"sessions": struct.sessions,
});
});
}).on('error', cb);
}
function storeSessions(files, formData) {
var id, name = formData.formName;
if ( !formData.identifier ) {
return;
}
id = formData.identifier;
Object.keys(files).forEach(function (path) {
var fileObj = files[path];
formData.sessions.forEach(function (data) {
if ( fileObj[id] && data[id] && fileObj[id] === data[id] ) {
fileObj[name] = fileObj[name] || [];
fileObj[name].push(data);
}
});
});
}
module.exports = function (opts) {
return function (files, metalsmith, done) {
var tasks = [],
metadata = metalsmith.metadata();
metadata.pooleapp = {};
Object.keys(opts.forms).forEach(function (formName) {
tasks.push(function (cb) {
fetchFormData(formName, opts.forms[formName], cb);
});
});
async.parallel(tasks, function (err, data) {
if ( err ) {
done(err);
return;
}
data.forEach(function (formData) {
metadata.pooleapp[formData.formName] = formData.sessions;
storeSessions(files, formData);
});
done();
});
};
};