From b17a81bfb0cb6b0fa46a8112d918474dc93d7bbf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bar=C4=B1=C5=9F=20Soner=20U=C5=9Fakl=C4=B1?= Date: Sun, 15 May 2022 21:23:23 -0400 Subject: [PATCH] fix: translate api error messages to user lang, closes #10623, --- public/src/client/topic/votes.js | 3 +-- src/controllers/helpers.js | 16 +++++++++++----- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/public/src/client/topic/votes.js b/public/src/client/topic/votes.js index e7813d9040..dcc225bd89 100644 --- a/public/src/client/topic/votes.js +++ b/public/src/client/topic/votes.js @@ -63,8 +63,7 @@ define('forum/topic/votes', [ delta: delta, }, function (err) { if (err) { - // TODO: err.message is currently hardcoded in helpers/api.js - if (err.message === 'A valid login session was not found. Please log in and try again.') { + if (!app.user.uid) { ajaxify.go('login'); return; } diff --git a/src/controllers/helpers.js b/src/controllers/helpers.js index 0d8d8762f1..1da9a1799a 100644 --- a/src/controllers/helpers.js +++ b/src/controllers/helpers.js @@ -460,7 +460,7 @@ helpers.formatApiResponse = async (statusCode, res, payload) => { Object.assign(response, { params }); } - const returnPayload = await helpers.generateError(statusCode, message); + const returnPayload = await helpers.generateError(statusCode, message, res); returnPayload.response = response; if (global.env === 'development') { @@ -471,7 +471,7 @@ helpers.formatApiResponse = async (statusCode, res, payload) => { res.status(statusCode).json(returnPayload); } else if (!payload) { // Non-2xx statusCode, generate predefined error - const returnPayload = await helpers.generateError(statusCode); + const returnPayload = await helpers.generateError(statusCode, null, res); res.status(statusCode).json(returnPayload); } }; @@ -495,15 +495,21 @@ async function generateBannedResponse(res) { return response; } -helpers.generateError = async (statusCode, message) => { +helpers.generateError = async (statusCode, message, res) => { + async function translateMessage(message) { + const { req } = res; + const settings = req.query.lang ? null : await user.getSettings(req.uid); + const language = String(req.query.lang || settings.userLang || meta.config.defaultLang); + return await translator.translate(message, language); + } if (message && message.startsWith('[[')) { - message = await translator.translate(message); + message = await translateMessage(message); } const payload = { status: { code: 'internal-server-error', - message: message || await translator.translate(`[[error:api.${statusCode}]]`), + message: message || await translateMessage(`[[error:api.${statusCode}]]`), }, response: {}, };