/**
* ClicData Auth flow
* @see https://app.clicdata.com/help/apidocumentation/api-getting-started
* Using library: https://github.com/gsuitedevs/apps-script-oauth2
* Resources > Libraries > Find a Library -> Enter: 1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF
*/
function run() {
/**
* Authorizes and makes a request to the ClicData API.
*/
// Complete all pending spreadsheet actions before adding responseURLs
SpreadsheetApp.flush();
// Base Server Address
var SERVER = \'https://api.clicdata.com/\';
//Schedule RecId\'s
var SCHEDULE_ID = \'RecId\';
// Data Set RecId\'s
var DATA_ID = \'RecId\';
// Task Options
var DATAREFRESH = \'/data/\' + DATA_ID + \'/reload\';
var RUNSCHEDULE = \'/schedule/\' + SCHEDULE_ID + \'/trigger\';
var serviceProject = getService();
Logger.log(serviceProject.hasAccess());
if (serviceProject.hasAccess()) {
var url = SERVER + DATAREFRESH; // Replace to POST different commands (see Task Options above)
Logger.log(serviceProject.getAccessToken());
// Try to load, if task is already running, wait, then try again
var runCheck = false // Set runCheck to false to initialize loop
restartloop: while (runCheck === false) {
try {
var response = UrlFetchApp.fetch(url, {
"method": "POST", // Change method to GET, POST, DELETE or PUT
headers: {
Authorization: \'Bearer \' + service.getAccessToken()
}
});
runCheck = true // Stop looping
} catch (e) {
if (e.message.indexOf(\'data is already being processed or is queued for processing\') > -1) {
Utilities.sleep(4000); // pause between refreshes for 4 second (trying to fix error code 400)
continue restartloop;
} else {
// Logs an ERROR message.
console.error(\'UrlFetchApp yielded an error: \' + e);
return; // Exits function and loop
break;
}
}
}
Logger.log(\'Success, data set \' + DATA_ID + \' has been reloaded.\') // Log Success!
} else {
Logger.log(service.getLastError());
// If Refresh Token has expired, reset authorization state then run authorization again (only required on first getService() call
reset();
run();
}
}
function reset() {
/**
* Reset the authorization state.
*/
getService().reset();
}
function getService() {
/**
* Configures the service.
*/
//Client_Credentials id and secret, obtain from ClicData Account settings
var CLIENT_ID = \'id\';
var CLIENT_SECRET = \'secret\';
return OAuth2.createService(\'ClicDataAdmin\')
// Set the endpoint URLs.
.setTokenUrl(\'https://api.clicdata.com/oauth20/token\')
// Set the client ID and secret.
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
// Sets the custom grant type to use.
.setGrantType(\'client_credentials\')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties());
}