eSentences/esentences.own
2024-07-15 16:39:31 +03:00

62 lines
1.7 KiB
Plaintext

use std, jdbc, functional, server
class Phrases {
def Phrases(database) {
conn = getConnection("jdbc:sqlite:" + database)
statement = conn.createStatement()
this.queryByWordsLength = conn.prepareStatement("
SELECT * FROM phrases
WHERE words BETWEEN ? AND ?
ORDER BY RANDOM()
LIMIT 1")
this.wordsByGroup = this.getWordsCountByGroup()
}
def getRandomPhrase() = this.readPhrase(
this.statement.executeQuery("SELECT * FROM phrases ORDER BY RANDOM() LIMIT 1")
)
def getRandomPhrase(minWords, maxWords = minWords) {
this.queryByWordsLength.setInt(1, minWords)
this.queryByWordsLength.setInt(2, maxWords)
return this.readPhrase(this.queryByWordsLength.executeQuery())
}
def readPhrase(rs) {
if (!rs.next()) {
return "Can't find any phrase"
}
words = rs.getInt("words")
return {
"id": rs.getInt("id"),
"words": words,
"en": rs.getString("en"),
"ru": rs.getString("ru"),
"countInGroup": this.wordsByGroup[words]
}
}
def getWordsCountByGroup() {
rs = statement.executeQuery(
"SELECT words, COUNT(*) FROM phrases GROUP BY words")
result = {}
while (rs.next()) {
result[rs.getInt(1)] = rs.getInt(2)
}
return result
}
}
db = new Phrases("phrases-easy.db")
server = newServer({"externalDirs": ["public"]})
server
.get("/shutdown", def(ctx) = server.stop().close())
.get("/phrase", def(ctx) = ctx.json(db.getRandomPhrase()))
.get("/phrase/{words}", def(ctx) {
words = parseInt(ctx.pathParam("words"))
ctx.json(db.getRandomPhrase(words))
})
.error(404, def(ctx) = ctx.result("Phrases not found"))
.start(8081)