-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
89 lines (72 loc) · 2.03 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
'use strict'
const Twitter = require('twitter')
const AWS = require('aws-sdk')
const moment = require('moment')
require('dotenv').config()
exports.handler = function (event, context, callback) {
let twitter = new Twitter({
consumer_key: process.env.TWITTER_CONSUMER_KEY,
consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
})
let params = {
screen_name: process.env.TWITTER_SCREEN_NAME
}
twitter.get('statuses/user_timeline', params, tweetHandler)
}
function tweetHandler (error, tweets, response) {
if (error) {
console.log(error, error.stack)
return
}
let latestTweet = moment(new Date(tweets[0].created_at))
let lastHour = moment().subtract(1, 'hours')
if (latestTweet.isBefore(lastHour)) {
console.log('No new tweets to upload.')
return
}
upload(tweets)
invalidate()
}
function upload (data) {
let s3 = new AWS.S3()
let params = {
Bucket: process.env.AWS_S3_BUCKET,
Key: process.env.AWS_S3_KEY,
Body: JSON.stringify(data),
ContentType: 'application/json',
CacheControl: process.env.AWS_S3_CACHE_CONTROL
}
console.log('Uploading to S3 bucket...')
s3.upload(params, function (error, data) {
if (error) {
console.log(error, error.stack)
} else {
console.log('Sucessfully uploaded tweets.json to S3')
}
})
}
function invalidate () {
const cloudfront = new AWS.CloudFront()
let params = {
DistributionId: process.env.AWS_CLOUDFRONT_DISTRIBUTION,
InvalidationBatch: {
CallerReference: '' + new Date().getTime(),
Paths: {
Quantity: 1,
Items: [
'/' + process.env.AWS_S3_KEY
]
}
}
}
console.log('Invalidating CloudFront distribution...')
cloudfront.createInvalidation(params, function (error, data) {
if (error) {
console.log(error, error.stack)
} else {
console.log('Sucessfully invalidated tweets.json on CloudFront')
}
})
}