BrAPIQuery.java

/*
 * Copyright 2024 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gringlobal.brapi.v2.query;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import lombok.Data;

@Data
public class BrAPIQuery {
	/**
	 * Used to request a specific page of data to be returned. The page indexing
	 * starts at 0 (the first page is 'page'= 0). Default is 0.
	 */
	private int page = 0;
	/** The size of the pages to be returned. Default is 1000. */
	private int pageSize = 1000;
	/** Name of the field to sort by. */
	private String[] sortBy;
	/** Sort order direction. Ascending/Descending. */
	private String sortOrder;

	public Pageable toPageRequest(int maxPageSize) {
		return PageRequest.of(page, Integer.min(pageSize, maxPageSize), Sort.Direction.ASC, "id");
	}

	public Pageable toPageRequest(int maxPageSize, Sort.Direction defaultDir, String... defaultSort) {
		return PageRequest.of(page, Integer.min(pageSize, maxPageSize), getDirection(defaultDir), getSortProperties(defaultSort));
	}

	/**
	 * Get sort direction or {@link Sort.Direction#ASC} if null.
	 *
	 * @param defaultDir the default dir
	 * @return sort direction or {@link Sort.Direction#ASC}
	 */
	private Sort.Direction getDirection(Sort.Direction defaultDir) {
		return sortOrder == null ? defaultDir : Sort.Direction.ASC;
	}

	/**
	 * Gets list of sort properties or provided defaults.
	 *
	 * @param defaultSortProps the default sort props
	 * @return provided properties or defaultSortProps
	 */
	private String[] getSortProperties(String[] defaultSortProps) {
		return sortBy == null || sortBy.length == 0 ? defaultSortProps : sortBy;
	}

	/**
	 * Handle nulls
	 * @param maxPageSize max page size
	 * @param page user-provided page
	 * @return pagination request trimmed to maxPageSize
	 */
  public static Pageable toPageRequest(int maxPageSize, BrAPIQuery page) {
		return page == null ? PageRequest.of(0, maxPageSize) : page.toPageRequest(maxPageSize);
  }

}