Is there is a way to "optionally" chain together filters for IGenericClient?
This code works:
import ca.uhn.fhir.model.api.IQueryParameterType;
import ca.uhn.fhir.rest.client.api.IGenericClient;
import ca.uhn.fhir.rest.gclient.ICriterion;
Optional<String> optFamilyName = Optional.of("Smith");
Optional<String> optGivenName = Optional.of("Peggy");
//optGivenName = Optional.empty();
ICriterion<StringClientParam> familyNameCriteria = null;
if (optFamilyName.isPresent()) {
familyNameCriteria = Patient.FAMILY.matches().value(optFamilyName.get());
}
ICriterion<StringClientParam> givenNameCriteria = null;
if (optGivenName.isPresent()) {
givenNameCriteria = Patient.GIVEN.matches().value(optGivenName.get());
}
// Perform a search
Bundle bundleSearchResult = client
.search()
.forResource(Patient.class)
.where(familyNameCriteria)
.and(givenNameCriteria)
.returnBundle(Bundle.class)
.execute();
But if I uncomment out
optGivenName = Optional.empty();
it will fail.
I understand why it is failing...that isn't the main point.
I'm trying to add items to the .where (and ? .add)... but when they are provided, not all the time.
Aka, adding "optional chaining" to the search method.
This below code does not work (will not compile), but kinda shows the intention:
Collection<ICriterion> allCriterias = new ArrayList<>();
ICriterion<StringClientParam> familyNameCriteria = null;
if (optFamilyName.isPresent()) {
familyNameCriteria = Patient.FAMILY.matches().value(optFamilyName.get());
allCriterias.add(familyNameCriteria);
}
ICriterion<StringClientParam> givenNameCriteria = null;
if (optGivenName.isPresent()) {
givenNameCriteria = Patient.GIVEN.matches().value(optGivenName.get());
allCriterias.add(familyNameCriteria);
}
// Perform a search
Bundle bundleSearchResult = client
.search()
.forResource(Patient.class)
.where(allCriterias) <<<<<<<<<< the items exist or do not exist i this List (this does NOT compile but shows the idea
.returnBundle(Bundle.class)
.execute();
implementation group: 'ca.uhn.hapi.fhir', name: 'hapi-fhir-structures-r4', version: hapiFhirVersion
implementation group: 'ca.uhn.hapi.fhir', name: 'hapi-fhir-client-okhttp', version: hapiFhirVersion
hapiFhirVersion = '5.2.0'