| 1 | // This script will return specified fields for all workbooks, using pagination and format the response as a table. |
| 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 | async function getAllWorkbooks() { |
| 16 | let hasMore = true; // Initialize hasMore to true for the first request |
| 17 | let nextPage = ''; // Initialize nextPage with an empty string for the first request |
| 18 | let currentPage = 0; // Initialize currentPage counter |
| 19 | let token = await getBearerToken(); // Obtain a bearer token for authentication |
| 20 | |
| 21 | |
| 22 | if (!token) { |
| 23 | console.error("Failed to obtain token, cannot proceed to fetch workbooks."); |
| 24 | return; // Exit the function if token acquisition fails |
| 25 | } |
| 26 | |
| 27 | while (hasMore) { |
| 28 | try { |
| 29 | currentPage++; // Increment the currentPage counter for each iteration |
| 30 | const url = `${baseURL}/workbooks${nextPage ? '?page=' + nextPage : ''}`; |
| 31 | console.log(`Fetching page ${currentPage} from Sigma: ${url}`); // Log the constructed URL before sending the request |
| 32 | |
| 33 | const response = await axios.get(url, { |
| 34 | headers: { Authorization: `Bearer ${token}` } // Authorization header with the bearer token |
| 35 | }); |
| 36 | |
| 37 | // Process current page workbooks for table display |
| 38 | console.log(`Workbooks on Page ${currentPage}:`); |
| 39 | const workbooksForTable = response.data.entries.map((workbook, index) => ({ |
| 40 | "#": index + 1, // Sequence number within the current page |
| 41 | Name: workbook.name, // Workbook name |
| 42 | Path: workbook.path, // Workbook path |
| 43 | LatestVersion: workbook.latestVersion // Latest version of the workbook |
| 44 | })); |
| 45 | |
| 46 | console.table(workbooksForTable); // Display the current page workbooks in table format |
| 47 | |
| 48 | hasMore = response.data.hasMore; // Update hasMore based on the response |
| 49 | nextPage = response.data.nextPage; // Update nextPage token/value for pagination |
| 50 | |
| 51 | } catch (error) { |
| 52 | console.error('Error fetching workbooks:', error); |
| 53 | break; // Exit the loop in case of an error |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | getAllWorkbooks().catch(error => { |
| 59 | console.error('Failed to fetch workbooks:', error); |
| 60 | }); |