com.xlrit.gears.server.graphql.DocumentResolver Maven / Gradle / Ivy
package com.xlrit.gears.server.graphql;
import java.util.List;
import com.xlrit.gears.base.model.Document;
import com.xlrit.gears.base.repository.Repository;
import com.xlrit.gears.base.util.Range;
import com.xlrit.gears.engine.repository.DocumentRepositoryImpl;
import com.xlrit.gears.engine.search.SearchAdapter;
import graphql.schema.DataFetchingEnvironment;
import jakarta.persistence.EntityGraph;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
@Controller
@RequiredArgsConstructor
public class DocumentResolver {
private static final Logger LOG = LoggerFactory.getLogger(DocumentResolver.class);
private final DocumentRepositoryImpl documentRepository;
private final SearchAdapter searchAdapter;
@PreAuthorize("isAuthenticated()")
@QueryMapping
public List documents(@Argument String filter, @Argument Range range, DataFetchingEnvironment env) {
LOG.info("documents(filter={}, range={})", filter, range);
EntityGraph loadGraph = documentRepository.createEntityGraph(env.getSelectionSet());
return documentRepository.query("""
SELECT d FROM Document d
WHERE d.publishedAt IS NOT NULL
AND (:filter = '' OR SEARCH('contains', :filter, d.title))
ORDER BY d.createdAt DESC
""")
.setParameter("filter", searchAdapter.adaptSearchTerm("contains", filter))
.setFirstResult(range.getStart())
.setMaxResults(range.getCount())
.setHint(Repository.LOADGRAPH, loadGraph)
.getResultList();
}
@PreAuthorize("isAuthenticated()")
@QueryMapping
public long documentsCount(@Argument String filter) {
return documentRepository.query(Long.class, """
SELECT COUNT(d) FROM Document d
WHERE d.publishedAt IS NOT NULL
AND (:filter = '' OR SEARCH('contains', :filter, d.title))
ORDER BY d.createdAt
""")
.setParameter("filter", searchAdapter.adaptSearchTerm("contains", filter))
.getSingleResult();
}
}