forked from MindscapeHQ/raygun4node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
raygun.offline.js
105 lines (83 loc) · 2.45 KB
/
raygun.offline.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*jshint unused:vars */
/*
* raygun
* https://github.com/MindscapeHQ/raygun4node
*
* Copyright (c) 2015 MindscapeHQ
* Licensed under the MIT license.
*/
'use strict';
var fs = require('fs');
var path = require('path');
var raygunTransport = require('./raygun.transport');
var OfflineStorage = function() {
var storage = this;
function _sendAndDelete(item) {
fs.readFile(
path.join(storage.cachePath, item),
'utf8',
function(err, cacheContents) {
raygunTransport.send(JSON.parse(cacheContents));
fs.unlink(path.join(storage.cachePath, item));
}
);
}
storage.init = function(offlineStorageOptions) {
if (!offlineStorageOptions && !offlineStorageOptions.cachePath) {
throw new Error("Cache Path must be set before Raygun can cache offline");
}
storage.cachePath = offlineStorageOptions.cachePath;
storage.cacheLimit = offlineStorageOptions.cacheLimit || 100;
if (!fs.existsSync(storage.cachePath)) {
fs.mkdirSync(storage.cachePath);
}
return storage;
};
storage.save = function(transportItem, callback) {
var filename = path.join(storage.cachePath, Date.now() + '.json');
delete transportItem.callback;
if (!callback) {
callback = function() {};
}
fs.readdir(storage.cachePath, function(err, files) {
if (err) {
console.log("[Raygun] Error reading cache folder");
console.log(err);
return callback(err);
}
if (files.length > storage.cacheLimit) {
console.log("[Raygun] Error cache reached limit");
return callback(null);
}
fs.writeFile(filename, JSON.stringify(transportItem), 'utf8',
function(err) {
if (!err) {
return callback(null);
}
console.log("[Raygun] Error writing to cache folder");
console.log(err);
return callback(err);
});
});
};
storage.retrieve = function(callback) {
fs.readdir(storage.cachePath, callback);
};
storage.send = function(callback) {
if (!callback) {
callback = function() {};
}
storage.retrieve(function(err, items) {
if (err) {
console.log("[Raygun] Error reading cache folder");
console.log(err);
return callback(err);
}
for (var i = 0; i < items.length; i++) {
_sendAndDelete(items[i]);
}
callback(err, items);
});
};
};
exports = module.exports = OfflineStorage;