forked from ember-fastboot/fastboot-s3-notifier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (54 loc) · 1.44 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
"use strict";
const AWS = require('aws-sdk');
const DEFAULT_POLL_TIME = 3 * 1000;
class S3Notifier {
constructor(options) {
this.ui = options.ui;
this.bucket = options.bucket;
this.key = options.key;
this.pollTime = options.poll || DEFAULT_POLL_TIME;
this.params = {
Bucket: this.bucket,
Key: this.key
};
this.s3 = new AWS.S3({
apiVersion: '2006-03-01',
signatureVersion: 'v4',
region: options.region
});
}
subscribe(notify) {
this.notify = notify;
return this.getCurrentLastModified()
.then(() => this.schedulePoll());
}
getCurrentLastModified() {
return this.s3.headObject(this.params).promise()
.then(data => {
this.lastModified = data.LastModified;
})
.catch(() => {
this.ui.writeError('error fetching S3 last modified; notifications disabled');
});
}
schedulePoll() {
setTimeout(() => {
this.poll();
}, this.pollTime);
}
poll() {
this.s3.headObject(this.params).promise()
.then(data => {
this.compareLastModifieds(data.LastModified);
this.schedulePoll();
});
}
compareLastModifieds(newLastModified) {
if (newLastModified.getTime() !== this.lastModified.getTime()) {
this.ui.writeLine('config modified; old=%s; new=%s', this.lastModified, newLastModified);
this.lastModified = newLastModified;
this.notify();
}
}
}
module.exports = S3Notifier;