UNPKG

3.82 kBJavaScriptView Raw
1var fs = require("fs");
2var coverageServer = require('node-coverage').admin;
3var path = require("path");
4
5module.exports = function (attesterServer, serverRoot) {
6 var listsPossibleReports = function () {
7 var list = [];
8 attesterServer.campaigns.forEach(function (campaign) {
9 var result = campaign.getCoverageResult();
10 if (result) {
11 list.push({
12 id: "Live campaign: " + campaign.id,
13 type: "live",
14 data: result
15 });
16 }
17 var previousReports = campaign.config['coverage-reports']['json-file'];
18 if (previousReports) {
19 previousReports.forEach(function (fileName) {
20 list.push({
21 id: "Stored report: " + path.basename(fileName, ".json"),
22 path: path.resolve(fileName),
23 type: "file"
24 });
25 });
26 }
27 });
28 return list;
29 };
30
31 var coverageViewer = coverageServer.createApp({
32 canMerge: false,
33 serverRoot: serverRoot,
34 docRoot: 'attester',
35 adminRoot: 'attester',
36 reportsList: function (callback) {
37 var possibleReports = listsPossibleReports();
38 var now = new Date();
39 var waitingCb = 1;
40 var callCallback = function () {
41 waitingCb--;
42 if (waitingCb === 0) {
43 var list = [];
44 possibleReports.forEach(function (report) {
45 if (report.type === "live") {
46 list.push({
47 id: report.id,
48 time: now.getTime(),
49 date: now.toString()
50 });
51 } else if (report.type === "file" && report.stats) {
52 list.push({
53 id: report.id,
54 time: report.stats.mtime.getTime(),
55 date: report.stats.mtime.toString()
56 });
57 }
58 });
59 callback(null, list);
60 }
61 };
62 possibleReports.forEach(function (possibleReport) {
63 if (possibleReport.type === "file") {
64 waitingCb++;
65 fs.stat(possibleReport.path, function (err, stats) {
66 if (!err) {
67 possibleReport.stats = stats;
68 }
69 callCallback();
70 });
71 }
72 });
73 callCallback();
74 },
75 readReport: function (reportId, callback) {
76 var possibleReports = listsPossibleReports();
77 var report = possibleReports.find(function (candidate) {
78 return candidate.id === reportId;
79 });
80 if (report && report.type === "live") {
81 callback(null, report.data);
82 } else if (report && report.type === "file") {
83 fs.readFile(report.path, 'utf-8', function (err, data) {
84 if (err) {
85 callback(err);
86 } else {
87 try {
88 var result = JSON.parse(data);
89 callback(null, result);
90 } catch (ex) {
91 callback(ex);
92 }
93 }
94 });
95 } else {
96 callback('Not found');
97 }
98 }
99 });
100 return coverageViewer.handle.bind(coverageViewer);
101};