1
0
mirror of https://github.com/oceanprotocol/community-numbers.git synced 2024-11-22 01:37:02 +01:00
community-numbers/api/networks/twitter.js

57 lines
1.4 KiB
JavaScript
Raw Normal View History

2021-11-09 09:36:02 +01:00
import axios from 'axios'
2023-05-24 12:47:53 +02:00
import fs from 'fs'
import { log, logError, Oauth1Helper } from '../utils'
import jsonDb from '../../jsonDb.json'
2019-05-14 20:59:15 +02:00
2020-06-16 11:12:27 +02:00
export default async function fetchTwitter() {
2023-05-24 12:47:53 +02:00
const url = 'https://api.twitter.com/2/users/me?user.fields=public_metrics'
2020-06-16 12:32:47 +02:00
const start = Date.now()
2023-05-24 12:47:53 +02:00
let followers = 0
const { twitter } = jsonDb
const currentTimestamp = Math.floor(Date.now() / 1000)
const oneDay = 60 * 60 * 24
const compareDatesBoolean = currentTimestamp - twitter.lastFetch > oneDay
if (!compareDatesBoolean) return { followers: twitter.followers }
const request = {
url,
method: 'GET'
}
const authHeader = await Oauth1Helper.getAuthHeaderForRequest(request)
const response = await axios.get(url, { headers: authHeader })
2019-05-14 20:59:15 +02:00
2020-06-16 12:32:47 +02:00
if (response.status !== 200) {
logError(`Non-200 response code from Twitter: ${response.status}`)
return null
}
2019-05-14 20:59:15 +02:00
2023-05-24 12:47:53 +02:00
if (response.data.data.public_metrics.followers_count === undefined)
return null
followers = response.data.data.public_metrics.followers_count
var stream = fs.createWriteStream('jsonDb.json')
const saveData = {
twitter: {
followers,
lastFetch: currentTimestamp
}
}
stream.once('open', function (fd) {
stream.write(JSON.stringify(saveData))
stream.end()
})
2019-05-14 20:59:15 +02:00
2020-06-16 12:32:47 +02:00
log(
2020-06-16 15:16:31 +02:00
'✓ Twitter. ' +
2020-06-16 12:32:47 +02:00
`Total: ${followers} followers. ` +
`Elapsed: ${new Date() - start}ms`
)
2019-05-14 20:59:15 +02:00
2020-06-16 12:32:47 +02:00
return { followers }
2019-05-14 20:59:15 +02:00
}