// Function assembles a complete URL with query parameters included
// IN: endpointURL : full URL of API endpoint, incl. protocol, host, and endpoint
//     paramsObject : object with query parameter names and optional values
//                    {
//                      instructor_id: instructor_id?.toString(),
//                      type: type // normal strings can be empty
//                    }
// OUT: URL object with query parameters included, ready to be used in the fetch API
export function assembleQueryParams(endpointURL: string, paramsObject: object) {
  const queryParams = new URLSearchParams();
  Object.entries(paramsObject).forEach(([key, value]) => {
    if (value) {
      queryParams.append(key, value);
    }
  });

  let url = new URL(endpointURL);
  url.search = queryParams.toString();
  return url;
}

// Custom error class meant for use when handling errors resulting from Fetch API calls
export class FetchError extends Error {
  // Members are nullable so that they don't need to be provided in cases of network errors
  response?: Response;
  status?: number;

  // USAGE: FetchError(message, response) where response is from Fetch API
  //        FetchError(message) for network errors
  constructor(message: string, response?: Response) {
    super(message);
    this.response = response;
    this.status = response?.status;
  }
}
