-
Notifications
You must be signed in to change notification settings - Fork 0
/
eight-track.js
71 lines (61 loc) · 2.28 KB
/
eight-track.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
import { HTTP } from 'meteor/http';
import { sinon } from 'meteor/practicalmeteor:sinon';
let fs;
let jsonfile;
if (Meteor.isServer) {
fs = Npm.require('fs');
jsonfile = Npm.require('jsonfile');
}
export class EightTrack {
static useCassette(cassetteName, block) {
const self = this;
const cassetteFileName = cassetteName + '.json';
const cassetteFilePath = self.cassettesDirectoryPath + cassetteFileName;
let cassettesDirectoryList = [];
// Read directory of cassettes or initialize an empty one.
try {
cassettesDirectoryList = fs.readdirSync(self.cassettesDirectoryPath);
} catch(e) {
if (e.message.match(RegExp('no such file or directory')))
fs.mkdirSync(self.cassettesDirectoryPath);
}
// Stub http methods. Preserve the original to be conditionally called inside wrapper.
const httpMethods = ['get', 'post', 'put', 'patch', 'del'];
httpMethods.forEach(methodName => {
const originalMethod = HTTP[methodName];
if (originalMethod.restore) originalMethod.restore();
sinon.stub(HTTP, methodName, (_args) => {
let response;
if (
cassettesDirectoryList.includes(cassetteFileName) &&
!self.cacheExpired(cassetteFilePath)
) {
response = jsonfile.readFileSync(cassetteFilePath);
} else {
if (!(_args instanceof Array))
_args = [_args];
response = originalMethod.apply(HTTP, _args);
jsonfile.writeFileSync(cassetteFilePath, response);
}
return response;
});
});
block();
httpMethods.forEach(methodName => { HTTP[methodName].restore(); });
}
// Is the cassette expired, according to the set reRecordInterval?
static cacheExpired(cassetteFilePath) {
const self = this;
const fileStats = fs.statSync(cassetteFilePath);
return (Date.now() - fileStats.birthtime.getTime()) >= self.reRecordInterval;
}
static get cassettesDirectoryPath() {
return process.env.PWD + '/eight-track-cassettes/';
}
// Determines expiration interval for cassettes. After they expire, they will
// be recreated with a new http request.
static get reRecordInterval() {
// For now, arbitrarily set all cassettes to expire in 24 hours from birth in milliseconds.
return 8.64e+7;
}
}