soundbirder/controllers/api.js
2024-02-04 07:07:37 +01:00

99 lines
2.7 KiB
JavaScript
Executable File

require('dotenv').config();
const debug = require('debug')('soundbirder:api');
const debugLocale = require('debug')('soundbirder:locale');
const debugResponses = require('debug')('soundbirder:api:responses');
const quizzController = require('./quizz');
const { getRegion } = require('./region');
const QUIZZ_SIZE = process.env.QUIZZ_SIZE ? process.env.QUIZZ_SIZE : 5;
async function region(req, res) {
let {lat, lon} = req.query;
lat = parseFloat(lat);
lon = parseFloat(lon);
const region = await getRegion(lat, lon);
res.json({
region
})
}
async function quizz(req, res) {
debug('Generating quizz');
const { region } = req.query;
req.session.region = region;
// debug(`Coordinates: ${lat}, ${lng}`);
const locale = req.i18n.locale;
debugLocale("Locale:", locale);
quizzController.getQuizzCached(region, locale, QUIZZ_SIZE)
.then(({ species, answer, audio }) => {
req.session.answer = answer;
res.json({ species, audio }).send();
debug("Quizz sent");
quizzController.cacheQuizz(); // Prepare the next question in advance.
debug("New quizz cached");
})
.catch(error => {
debug("Faced error while generating quizz");
debug(error)
});
}
function check(req, res) {
let answer, correct;
try {
answer = req.query.species;
correct = req.session.answer;
} catch (error) {
console.error(error);
}
let result = {};
try {
if (correct === undefined) {
console.error("No answer found in session");
} else if (answer === correct.speciesCode) {
debug("Correct answer");
result = {
correct: true,
message: req.i18n.__('Correct!'),
answer: correct
};
} else {
debug("Wrong answer");
result = {
correct: false,
message: req.i18n.__('Wrong!'),
answer: correct
};
}
} catch (error) {
console.error(error);
}
res.json(result);
}
async function birdSpeciesCompletion(req, res) {
const { q } = req.query;
const locale = req.i18n.locale;
const region = req.session.region;
if (region === undefined) {
res.status(400).json({error: "Your session is not associated with any region yet"});
return;
}
if (q === undefined) {
res.status(400).json({error: "No query provided"});
return;
}
let speciesCompletion = await quizzController.getSpeciesCompletion(region, locale, q);
res.json(speciesCompletion);
}
const game = {
check,
quizz,
birdSpeciesCompletion
}
module.exports = {
game,
region
}