All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.sphere.internal.request.FetchRequestBasedOnQuery Maven / Gradle / Ivy

There is a newer version: 0.72.1
Show newest version
package io.sphere.internal.request;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import io.sphere.internal.util.Log;
import io.sphere.internal.util.Util;
import io.sphere.client.FetchRequest;
import io.sphere.client.QueryRequest;
import io.sphere.client.model.QueryResult;

/** Request that fetches a single object, implemented using a query endpoint.
 * Used when fetching products by slug. */
public class FetchRequestBasedOnQuery implements FetchRequest  {
    private QueryRequest underlyingQueryRequest;

    public FetchRequestBasedOnQuery(QueryRequest underlyingQueryRequest) {
        this.underlyingQueryRequest = underlyingQueryRequest;
    }

    @Override public Optional fetch() {
        return Util.sync(fetchAsync());
    }

    @Override public ListenableFuture> fetchAsync() {
        return Futures.transform(this.underlyingQueryRequest.fetchAsync(), new Function, Optional>() {
            public Optional apply(QueryResult result) {
                assert result != null;
                if (result.getCount() == 0) return Optional.absent();
                if (result.getCount() > 1) {
                    Log.warn("Fetch query returned more than one object: " + FetchRequestBasedOnQuery.this.underlyingQueryRequest);
                }
                return Optional.of(result.getResults().get(0));
            }
        });
    }

    @Override public FetchRequest expand(String... paths) {
        underlyingQueryRequest = this.underlyingQueryRequest.expand(paths);
        return this;
    }

    // testing purposes
    public QueryRequest getUnderlyingQueryRequest() {
        return underlyingQueryRequest;
    }

    // logging and debugging purposes
    @Override public String toString() {
        return getUnderlyingQueryRequest().toString();
    }

    public static  FetchRequest asFetchRequest(final QueryRequest queryRequest) {
        return new FetchRequestBasedOnQuery(queryRequest);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy