DEV Community

Khan
Khan

Posted on

Why isn't the enrollment API working in my code?

In our staff training course, a new user can create a sandbox for themselves. I'm using the Brightspace (D2L) Whoami, Enrollment, and Create Course APIs. While Whoami and Create Course are working as
expected, the Enrollment API is not. I'm utilising the Enrollment API to search for a sandbox if it's already created and to avoid duplication.
Do you have any advice? Please see the part of the code below.

// Define the base URL for the Brightspace API endpoint for enrollments
const baseURL = https://example.com/d2l/api/lp/1.44/enrollments/myenrollments/;

// Define the URL for fetching enrollments with the bookmark parameter
let enrollmentsURL = `${baseURL}?bookmark=6606`;

// Array to store all enrollments
let allEnrollments = [];

// Fetch all pages of enrollments
while (enrollmentsURL) {
  const enrollmentsResponse = await fetch(enrollmentsURL);
  const enrollmentsData = await enrollmentsResponse.json(); // Define enrollmentsData here

  // Add fetched enrollments to the array
  allEnrollments = allEnrollments.concat(enrollmentsData.Items);

  // Check if there are more pages
  if (enrollmentsData.PagingData && enrollmentsData.PagingData.bookmark) {
    enrollmentsURL = `${baseURL}?bookmark=${enrollmentsData.PagingData.bookmark}`;
  } else {
    enrollmentsURL = null;
  }
}
Enter fullscreen mode Exit fullscreen mode

// Check if the course already exists in the user's enrollments
const courseExists = allEnrollments.some(enrollment => enrollment && enrollment.CourseName === uniqueName);

if (courseExists) {
  // Display message if the course already exists
  document.getElementById("message").textContent = `Course "${uniqueName}" already exists in your enrollment.`;
  return; // Exit function if course already exists
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)