Created
November 26, 2023 01:30
-
-
Save yvonnel098/b80f6799c4e4dabe80347e46b4322b9e to your computer and use it in GitHub Desktop.
Calling Twilio API to retrieve and paginate pending tasks using yargs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const axios = require('axios'); | |
require('yargs') | |
.command( | |
'exec', | |
'get Twilio pending tasks with pagination', | |
yargs => { | |
yargs.options({ | |
'twilio-account-sid':{ | |
describe: 'Twilio Account SID', | |
string: true, | |
demandOption: true | |
}, | |
'twilio-token':{ | |
describe: 'Twilio Token', | |
string: true, | |
demandOption: true | |
}, | |
'workspace-sid':{ | |
describe: 'Twilio Workspace SID', | |
string: true, | |
demandOption: true | |
}, | |
'queue-sid':{ | |
describe: 'Twilio Task Queue SID', | |
string: true, | |
demandOption: true | |
} | |
}) | |
}, | |
({ | |
twilioAccountSid, | |
twilioToken, | |
twilioWorkspaceSid, | |
queueSid | |
})=>{ | |
executeec( | |
twilioAccountSid, | |
twilioToken, | |
twilioWorkspaceSid, | |
queueSid | |
) | |
.then(console.log(`done`)) | |
.catch(error=> | |
console.log(`Errored out ${error}`)) | |
} | |
) | |
.env() | |
.help() | |
.demandCommand(1, 'Please provice a command to execute') | |
.strictCommands().argv; | |
const MAX_RETRIES = 5; | |
async function executeec( | |
twilioAccountSid, | |
twilioToken, | |
twilioWorkspaceSid, | |
queueSid | |
) { | |
let page_size=50; | |
let page_count=0; | |
let nextPageUrl; | |
let currentUrl = `https://taskrouter.twilio.com/v1/Workspace/${twilioWorkspaceSid}/Tasks`; | |
let data; | |
try{ | |
do { | |
data = await axios.get(currentUrl, { | |
params:{ | |
PageSize: page_size, | |
AssignmentStatus: 'pending', | |
TaskQueueSid: queueSid, | |
}, | |
auth:{ | |
username: twilioAccountSid, | |
password: twilioToken | |
} | |
}) | |
page_count++; | |
for (let i=0; i<data.data.tasks.length; i++){ | |
let taskSid=data.data.tasks[i].taskSid; | |
let attributes=JSON.parse(data.data.tasks[i].attributes); | |
console.log(taskSid); | |
} | |
console.log("page:", page_count); | |
nextPageUrl = (data.data.meta.next_page_url)? (data.data.meta.next_page_url):null; | |
if (!nextPageUrl){ | |
console.log("no more tasks"); | |
break; | |
} | |
currentUrl = nextPageUrl; | |
} while (page_count<10); | |
}catch (err){ | |
console.error("Error:", err); | |
} | |
return; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Twilio nodejs SDK does not paginate tasks. This is a way to get around it by calling the REST API interface. Note, the code is hard coded to up to 10 pages at 50 tasks each. Also, the tasks status is hard coded to pending.