Skip to content

Instantly share code, notes, and snippets.

@hamg26
Created January 4, 2022 22:32
Show Gist options
  • Save hamg26/990359092be58eac740fd4289fdc398d to your computer and use it in GitHub Desktop.
Save hamg26/990359092be58eac740fd4289fdc398d to your computer and use it in GitHub Desktop.
Rate limited API consumption (FIFO)
const https = require('https')
const HOST = "";
const PATH = ""
const TOKEN = ""
const RATE_LMIT = 10;
const RATE_INTERVAL = 1000; //ms
const post = (phone, code) => new Promise((resolve, reject) => {
const data = JSON.stringify({
"recipient_type": "individual",
"to": phone,
"type": "text",
"text": {
"body": `Hello, your code is: ${code}`
}
});
const options = {
host: HOST,
path: PATH,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${TOKEN}`
}
}
const req = https.request(options, res => {
res.on('data', d => {
resolve(res.statusCode);
})
})
req.on('error', error => {
reject(error);
})
req.write(data)
req.end()
});
const queue = []
const consumer = () => {
for (let i = 1; i<=RATE_LMIT; i++) {
const request = queue.shift();
if (request) {
post(request.phone, request.code).then(console.log, console.error);
}
}
}
const orchestrator = (request) => {
queue.push(request);
}
setInterval(consumer, RATE_INTERVAL);
for (let i=1; i<=100; i++) {
orchestrator({phone:'123456', code:i});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment