|
/** |
|
* This is a simple Node.JS script using the Front GET /events API endpoint (https://dev.frontapp.com/reference/get_events) |
|
* fetching all "message" type events from the requester's Front account. |
|
* Requests are issued using Axios (https://www.npmjs.com/package/axios). |
|
* The script will respect your Front API rate limit. |
|
* |
|
* Sign up at https://front.com |
|
* |
|
* |
|
* To run this script, save the file locally as a .js file (front_events.js). |
|
* Ensure axios is installed; |
|
* `npm i axios` |
|
* Replace the YOUR_API_TOKEN string with your Front API token |
|
* Run the script; |
|
* `node front_events.js` |
|
*/ |
|
|
|
const axios = require('axios'); |
|
const headers = { |
|
'Accept': 'application/json', |
|
'Authorization': 'Bearer YOUR_API_TOKEN', |
|
}; |
|
|
|
// Max number of results to return per page |
|
const LIMIT = 5; |
|
// Your query. This example fetches all message type events (inbound, outbound, and outbound reply) |
|
const query = `q[types]=inbound&q[types]=outbound&q[types]=out_reply`; |
|
|
|
/* Main function */ |
|
async function run() { |
|
await request(`https://api2.frontapp.com/events?${query}&limit=${LIMIT}`); |
|
} |
|
|
|
/** |
|
* Performs API request, and loops while new pages are available |
|
*/ |
|
async function request(url) { |
|
let response = await axios.get(url, {headers}); |
|
|
|
/* Pass off the API response to our handler */ |
|
await handleResponse(response); |
|
|
|
/* Maybe snooze if we're approaching the rate limit */ |
|
await checkRateLimit(response.headers); |
|
|
|
if (response.data._pagination.next) { |
|
await request(response.data._pagination.next); |
|
} |
|
|
|
return; |
|
} |
|
|
|
/** |
|
* Helper function to sleep for a number of milliseconds. |
|
* sleep(5000) will sleep for 5 seconds. |
|
*/ |
|
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); |
|
|
|
/** |
|
* Check the API rate limit headers, and wait before allowing a new request if necessary |
|
* See Rate Limiting docs for details: |
|
* https://dev.frontapp.com/docs/rate-limiting |
|
*/ |
|
async function checkRateLimit(headers) { |
|
if (Number(headers['Retry-After'])) { |
|
console.log(`Hit API rate limit. Snoozing for ${headers['Retry-After']} seconds`); |
|
await sleep(Number(headers['Retry-After']) * 1000); |
|
} |
|
} |
|
|
|
/** |
|
* Generic method to handle responses from the API. |
|
* This example prints the ID and type of each event to console.log(). |
|
*/ |
|
async function handleResponse(response) { |
|
let results = response.data._results; |
|
|
|
results.forEach((r) => console.log(`ID: ${r.id}, Type: ${r.type}`)); |
|
|
|
return; |
|
} |
|
|
|
run(); |