-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.js
More file actions
75 lines (62 loc) · 2.08 KB
/
handler.js
File metadata and controls
75 lines (62 loc) · 2.08 KB
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
'use strict'
const fetch = require('node-fetch')
const { URLSearchParams } = require('url')
const url = 'https://api.twitter.com/1.1/statuses/user_timeline.json'
const params = new URLSearchParams({
screen_name: 'borderlands',
tweet_mode: 'extended',
count: 100
})
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true
}
function getRegex (platform) {
switch (platform) {
case 'xbox':
return /XBOne.*(?<shiftCode>([A-Z0-9]{5}-){4}[A-Z0-9]{5}).*/i
case 'ps':
return /PS.*(?<shiftCode>([A-Z0-9]{5}-){4}[A-Z0-9]{5}).*/i
default:
return /PC.*(?<shiftCode>([A-Z0-9]{5}-){4}[A-Z0-9]{5}).*/i
}
}
function getShiftCode (text, regex) {
// Check most recent style of tweets
let result = /All\s+Platforms.*(?<shiftCode>([A-Z0-9]{5}-){4}[A-Z0-9]{5}).*/is.exec(text)
if (result) {
return result.groups.shiftCode
}
// Check for Borderlands 3
result = /Borderlands\s+3.*(?<shiftCode>([A-Z0-9]{5}-){4}[A-Z0-9]{5}).*/is.exec(text)
if (result) {
return result.groups.shiftCode
}
// Check legacy platform specific tweets
result = regex.exec(text)
if (result) {
return result.groups.shiftCode
}
return null
}
async function handler (event) {
const regex = getRegex(event.path.substring(1))
const headers = { headers: { Authorization: `Bearer ${process.env.TOKEN}` } }
return fetch(`${url}?${params.toString()}`, headers)
.then((response) => response.json())
.then((tweets) => {
const tweet = tweets.find((tweet) => getShiftCode(tweet.retweeted_status ? tweet.retweeted_status.full_text : tweet.full_text, regex))
if (tweet) {
return Promise.resolve(getShiftCode(tweet.retweeted_status ? tweet.retweeted_status.full_text : tweet.full_text, regex))
} else {
return Promise.reject(new Error('No SHiFT code found!'))
}
})
.then((shiftCode) => ({ statusCode: 200, headers: corsHeaders, body: JSON.stringify(shiftCode) }))
.catch(() => ({ statusCode: 204, headers: corsHeaders }))
}
module.exports = {
fetch: handler,
getShiftCode,
getRegex
}