peer-at-code-backend/src/be/jeffcheasey88/peeratcode/routes/ChapterList.java
TheNagaki 80563cd86e Added ChapterElement and ChapterList as routes to respectively get a chapter by id and all the chapters.
Removed DatabaseQueries class and added DatabaseRepo to contain all the database queries; Edited PuzzleElement to remove all database-related code.
2023-02-09 22:42:33 +01:00

46 lines
1.4 KiB
Java

package be.jeffcheasey88.peeratcode.routes;
import be.jeffcheasey88.peeratcode.model.Chapter;
import be.jeffcheasey88.peeratcode.repository.DatabaseRepo;
import be.jeffcheasey88.peeratcode.webserver.HttpReader;
import be.jeffcheasey88.peeratcode.webserver.HttpUtil;
import be.jeffcheasey88.peeratcode.webserver.HttpWriter;
import be.jeffcheasey88.peeratcode.webserver.Response;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ChapterList implements Response {
private final DatabaseRepo databaseRepo;
public ChapterList(DatabaseRepo databaseRepo) {
this.databaseRepo = databaseRepo;
}
@Override
public void exec(Matcher matcher, HttpReader reader, HttpWriter writer) throws Exception {
HttpUtil.responseHeaders(writer, 200, "Access-Control-Allow-Origin: *");
List<Chapter> allChapters = databaseRepo.getAllChapters();
if (allChapters != null) {
JSONArray chaptersJSON = new JSONArray();
for (Chapter chapter : allChapters) {
JSONObject chapterJSON = new JSONObject();
chapterJSON.put("id", chapter.getId());
chapterJSON.put("name", chapter.getName());
chaptersJSON.add(chapterJSON);
}
writer.write(chaptersJSON.toJSONString());
}
writer.flush();
writer.close();
}
@Override
public Pattern getPattern() {
return Pattern.compile("^\\/chapters$");
}
}