105 lines
2.8 KiB
JavaScript
Executable File
105 lines
2.8 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 question(req, res) {
|
|
debug('Generating question');
|
|
const { region } = req.query;
|
|
req.session.region = region;
|
|
const locale = req.i18n.locale;
|
|
debugLocale("Locale:", locale);
|
|
quizzController.getQuestionCached(region, locale, QUIZZ_SIZE)
|
|
.then(({ species, answer, audio }) => {
|
|
req.session.answer = answer;
|
|
res.json({ species, audio }).send();
|
|
debug("Quizz sent");
|
|
quizzController.cacheQuestion(); // Prepare the next question in advance.
|
|
debug("New quizz cached");
|
|
})
|
|
.catch(error => {
|
|
debug("Faced error while generating quizz");
|
|
debug(error)
|
|
});
|
|
}
|
|
|
|
|
|
async function quizz(req, res) {
|
|
const { region } = req.query;
|
|
req.session.region = region;
|
|
if (region == undefined) {
|
|
res.status(400).json({
|
|
error: 'No region specified',
|
|
})
|
|
}
|
|
const locale = req.i18n.locale;
|
|
if (locale == undefined) {
|
|
res.status(400).json(
|
|
{
|
|
error: 'No locale specified'
|
|
}
|
|
)
|
|
}
|
|
quizzController.generateQuizz(region, locale, 10)
|
|
.then(({ questions, answers, propositions }) => {
|
|
res.json({questions, answers, propositions }).send();
|
|
});
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
const game = {
|
|
check,
|
|
question,
|
|
quizz,
|
|
}
|
|
|
|
module.exports = {
|
|
game,
|
|
region
|
|
} |