Rate limiting aware data setup

This commit is contained in:
Dan Caseley 2020-07-27 10:31:38 +01:00
parent 4171967de3
commit d115604270
1 changed files with 24 additions and 6 deletions

View File

@ -10,9 +10,27 @@ const rocketchat = axios.create({
}
})
const sleep = async (ms) => {
return new Promise(res => setTimeout(res, ms));
}
const rocketchatRequest = async (method, url, data, config) => {
if (method == 'get'){
data = config //Because axios.get doesn't take data param, but this function does, and I'm about to pass ordered params...
}
let response = await rocketchat[method](url, data, config)
if (response.status == 429) {
const resetTime = parseInt(response.headers['x-ratelimit-reset'])
const sleepTime = (resetTime - new Date().getTime()) + 250 //In case of reduced precision
await sleep(sleepTime)
response = await rocketchatRequest(method, url, data, config)
}
return response
}
const login = async (username, password) => {
console.log(`Logging in as user ${username}`)
const response = await rocketchat.post('login', {
const response = await rocketchatRequest('post', 'login', {
"user": username,
"password": password
})
@ -25,7 +43,7 @@ const login = async (username, password) => {
const createUser = async (username, password, name, email) => {
console.log(`Creating user ${username}`)
try {
await rocketchat.post('users.create', {
await rocketchatRequest('post', 'users.create', {
"username": username,
"password": password,
"name": name,
@ -40,12 +58,12 @@ const createUser = async (username, password, name, email) => {
const createChannelIfNotExists = async (channelname) => {
console.log(`Creating public channel ${channelname}`)
try {
await rocketchat.post('channels.create', {
await rocketchatRequest('post', 'channels.create', {
"name": channelname
})
} catch (createError) {
try { //Maybe it exists already?
await rocketchat.get(`channels.info?roomName=${channelname}`)
await rocketchatRequest('get', `channels.info?roomName=${channelname}`)
} catch (infoError) {
console.log(JSON.stringify(createError))
console.log(JSON.stringify(infoError))
@ -57,12 +75,12 @@ const createChannelIfNotExists = async (channelname) => {
const createGroupIfNotExists = async (groupname) => {
console.log(`Creating private group ${groupname}`)
try {
await rocketchat.post('groups.create', {
await rocketchatRequest('post', 'groups.create', {
"name": groupname
})
} catch (createError) {
try { //Maybe it exists already?
await rocketchat.get(`group.info?roomName=${groupname}`)
await rocketchatRequest('get', `group.info?roomName=${groupname}`)
} catch (infoError) {
console.log(JSON.stringify(createError))
console.log(JSON.stringify(infoError))