Skip to content

Instantly share code, notes, and snippets.

@NotArchon
Created May 8, 2023 15:20
Show Gist options
  • Save NotArchon/582c24ef295803945e89a9294b137d85 to your computer and use it in GitHub Desktop.
Save NotArchon/582c24ef295803945e89a9294b137d85 to your computer and use it in GitHub Desktop.
package com.neox.web.model.game.requests;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Projections;
import com.mongodb.client.model.Sorts;
import com.neox.web.Neox;
import com.neox.web.model.game.GameRequest;
import com.neox.web.pojo.VoteDoc;
import io.archon.webserver.network.HttpAsyncRequest;
import io.archon.webserver.network.messages.JsonMessage;
import io.archon.webserver.network.messages.StatusMessage;
import io.netty5.handler.codec.http.HttpResponseStatus;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.experimental.FieldDefaults;
import java.util.ArrayList;
import java.util.List;
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
@NoArgsConstructor(force = true, access = AccessLevel.PRIVATE) // needed for default values
public class ClaimVotes implements GameRequest {
String userId;
long lastClaimedMs; // 0 if never claimed before
@Override
public void handle(HttpAsyncRequest httpReq) {
if(userId == null) {
httpReq.write(new StatusMessage(HttpResponseStatus.BAD_REQUEST));
return;
}
MongoCollection<VoteDoc> collection = Neox.getNode().getMongoDatabase()
.getCollection("votes", VoteDoc.class);
List<Long> votes = collection
.find(Filters.and(
Filters.eq("user_id", userId),
Filters.gt("queued_at", lastClaimedMs)
))
.sort(Sorts.ascending("queued_at")) // newest vote will be at end
.projection(Projections.fields(
Projections.include("queued_at"),
Projections.excludeId()
))
.limit(50) // generous limit
.map(VoteDoc::queuedAt).into(new ArrayList<>());
long newestMs = votes.isEmpty() ? 0 : votes.get(votes.size() - 1);
Response response = new Response();
response.lastClaimedMs = Math.max(newestMs, lastClaimedMs);
response.count = votes.size();
httpReq.write(JsonMessage.normal(response));
}
private static final class Response {
long lastClaimedMs;
int count;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment