| 1 | // This script lists all workbooks, returning name, URL, URL ID, and version |
| 2 | |
| 3 | // 1: Load environment variables from a specific .env file for configuration |
| 4 | require('dotenv').config({ path: 'sigma-api-recipes/.env' }); |
| 5 | |
| 6 | // 2: Import the function to obtain a bearer token from the authenticate-bearer module |
| 7 | const getBearerToken = require('../get-access-token'); |
| 8 | |
| 9 | // 3: Import Axios for making HTTP requests |
| 10 | const axios = require('axios'); |
| 11 | |
| 12 | // 4: Load use-case specific variables from environment variables |
| 13 | const baseURL = process.env.baseURL; // Your base URL |
| 14 | |
| 15 | // Define an asynchronous function to fetch workbooks with pagination |
| 16 | async function fetchWorkbooksWithPagination(url, accessToken) { |
| 17 | let results = []; |
| 18 | let nextPageToken = ''; // Initialize pagination token |
| 19 | do { |
| 20 | const fullUrl = `${url}${nextPageToken ? `?page=${nextPageToken}` : ''}`; |
| 21 | console.log(`Fetching: ${fullUrl}`); |
| 22 | try { |
| 23 | const response = await axios.get(fullUrl, { |
| 24 | headers: { 'Authorization': `Bearer ${accessToken}` }, |
| 25 | }); |
| 26 | results = [...results, ...response.data.entries]; |
| 27 | nextPageToken = response.data.nextPage; // Update the nextPageToken with the next page value |
| 28 | } catch (error) { |
| 29 | console.error(`Error fetching workbooks: ${error}`); |
| 30 | break; // Exit loop on error |
| 31 | } |
| 32 | } while (nextPageToken); // Continue fetching pages until there's no nextPageToken |
| 33 | return results; |
| 34 | } |
| 35 | |
| 36 | // Define an asynchronous function to list workbooks |
| 37 | async function listWorkbooks() { |
| 38 | const accessToken = await getBearerToken(); |
| 39 | if (!accessToken) { |
| 40 | console.error('Failed to obtain Bearer token.'); |
| 41 | return; |
| 42 | } |
| 43 | |
| 44 | try { |
| 45 | // Fetch all workbooks with pagination |
| 46 | const workbooks = await fetchWorkbooksWithPagination(`${baseURL}/workbooks`, accessToken); |
| 47 | |
| 48 | if (workbooks.length > 0) { |
| 49 | // Display information for each workbook |
| 50 | workbooks.forEach((workbook, index) => { |
| 51 | console.log(`#${index + 1}: Name: ${workbook.name}, URL: ${workbook.url}, URL ID: ${workbook.workbookUrlId}, Latest Version: ${workbook.latestVersion}`); |
| 52 | }); |
| 53 | } else { |
| 54 | console.log('No workbooks found.'); |
| 55 | } |
| 56 | } catch (error) { |
| 57 | console.error('Error listing workbooks:', error); |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | // Execute the function to list workbooks if this script is run directly |
| 62 | if (require.main === module) { |
| 63 | listWorkbooks(); |
| 64 | } |
| 65 | |
| 66 | // Export the listWorkbooks function for reuse in other modules |
| 67 | module.exports = listWorkbooks; |