net.worcade.client.internal.WorcadeQuery Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of api-client Show documentation
Show all versions of api-client Show documentation
A library for interacting with the Worcade API
// Copyright (c) 2017, Worcade. Please see the AUTHORS file for details.
// All rights reserved. Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package net.worcade.client.internal;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.ToString;
import net.worcade.client.query.EntityField;
import net.worcade.client.query.Query;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
@AllArgsConstructor(access = AccessLevel.PACKAGE) @ToString
public class WorcadeQuery implements Query {
private final Set fields;
private final Multimap filter;
private final List order;
private final int limit;
String toQueryString() {
StringBuilder sb = new StringBuilder("?limit=" + limit);
for (EntityField field : fields) {
sb.append("&field=").append(field.name());
}
for (Map.Entry extends EntityField, String> filter : filter.entries()) {
sb.append("&").append(filter.getKey().name()).append("=").append(Util.escapeUrlQueryParameter(filter.getValue()));
}
for (Order o : order) {
sb.append("&order=").append(o.ascending ? "" : "-").append(o.field.name());
}
return sb.toString();
}
public static & EntityField> Query.Builder builder() {
return new Builder<>();
}
static class Builder & EntityField> implements Query.Builder {
final Set fields = Sets.newHashSet();
final ImmutableMultimap.Builder filter = ImmutableMultimap.builder();
final ImmutableList.Builder order = ImmutableList.builder();
int limit = 10;
@Override
@SafeVarargs
public final Builder fields(T... fields) {
Collections.addAll(this.fields, fields);
return this;
}
@Override
public Builder fields(Collection fields) {
this.fields.addAll(fields);
return this;
}
@Override
public Builder filter(T field, String value) {
filter.put(field, value);
return this;
}
@Override
public Builder order(T field, boolean ascending) {
order.add(new Order(field, ascending));
return this;
}
@Override
public Builder limit(int limit) {
this.limit = Math.min(Math.max(1, limit), 100);
return this;
}
@Override
public WorcadeQuery build() {
return new WorcadeQuery<>(ImmutableSet.copyOf(fields), filter.build(), order.build(), limit);
}
}
@AllArgsConstructor(access = AccessLevel.PRIVATE) @ToString
static class Order {
private final EntityField field;
private final boolean ascending;
}
}