peer-at-code-backend/src/dev/peerat/backend/routes/BadgeDetails.java

47 lines
No EOL
1.5 KiB
Java

package dev.peerat.backend.routes;
import java.util.Base64;
import java.util.regex.Matcher;
import org.json.simple.JSONObject;
import dev.peerat.backend.bonus.extract.RouteDoc;
import dev.peerat.backend.model.Badge;
import dev.peerat.backend.repository.DatabaseRepository;
import dev.peerat.framework.Context;
import dev.peerat.framework.HttpReader;
import dev.peerat.framework.HttpWriter;
import dev.peerat.framework.Response;
import dev.peerat.framework.Route;
public class BadgeDetails implements Response {
private final DatabaseRepository databaseRepo;
public BadgeDetails(DatabaseRepository databaseRepo) {
this.databaseRepo = databaseRepo;
}
@RouteDoc(path = "/badge/<id>", responseCode = 200, responseDescription = "JSON contenant les informations du badge")
@RouteDoc(responseCode = 400, responseDescription = "Aucun id donner")
@Route(path = "^\\/badge\\/([0-9]+)$", needLogin = true)
public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception {
if (matcher.groupCount() > 0) {
int badgeId = Integer.parseInt(matcher.group(1));
Badge badge = databaseRepo.getBadge(badgeId);
JSONObject badgeJSON = new JSONObject();
if (badge != null) {
badgeJSON.put("name", badge.getName());
if (badge.getLogo() != null)
badgeJSON.put("logo", Base64.getEncoder().encodeToString(badge.getLogo()));
badgeJSON.put("level", badge.getLevel());
}
context.response(200);
writer.write(badgeJSON.toJSONString().replace("\\", ""));
} else {
context.response(400);
}
}
}