refactor: move API banned response handler to separate internal method

v1.18.x
Julian Lam 4 years ago
parent afb26bfe48
commit 906d7d734b

@ -1,5 +1,6 @@
'use strict'; 'use strict';
const colors = require('colors/safe');
const nconf = require('nconf'); const nconf = require('nconf');
const validator = require('validator'); const validator = require('validator');
const querystring = require('querystring'); const querystring = require('querystring');
@ -361,21 +362,9 @@ helpers.formatApiResponse = async (statusCode, res, payload) => {
// Update status code based on some common error codes // Update status code based on some common error codes
switch (payload.message) { switch (payload.message) {
case '[[error:user-banned]]': { case '[[error:user-banned]]':
const [reason, expiry] = await Promise.all([ Object.assign(response, await generateBannedResponse(res));
user.bans.getReason(res.req.uid), // intentional fall through
user.getUserField(res.req.uid, 'banned:expire'),
]);
response.reason = reason;
if (expiry) {
Object.assign(response, {
expiry,
expiryISO: new Date(expiry).toISOString(),
expiryLocaleString: new Date(expiry).toLocaleString(),
});
}
} // intentional fall through
case '[[error:no-privileges]]': case '[[error:no-privileges]]':
statusCode = 403; statusCode = 403;
@ -391,6 +380,7 @@ helpers.formatApiResponse = async (statusCode, res, payload) => {
if (global.env === 'development') { if (global.env === 'development') {
returnPayload.stack = payload.stack; returnPayload.stack = payload.stack;
process.stdout.write(`[${colors.yellow('api')}] Exception caught, error with stack trace follows:\n`);
process.stdout.write(payload.stack); process.stdout.write(payload.stack);
} }
res.status(statusCode).json(returnPayload); res.status(statusCode).json(returnPayload);
@ -400,6 +390,25 @@ helpers.formatApiResponse = async (statusCode, res, payload) => {
} }
}; };
async function generateBannedResponse(res) {
const response = {};
const [reason, expiry] = await Promise.all([
user.bans.getReason(res.req.uid),
user.getUserField(res.req.uid, 'banned:expire'),
]);
response.reason = reason;
if (expiry) {
Object.assign(response, {
expiry,
expiryISO: new Date(expiry).toISOString(),
expiryLocaleString: new Date(expiry).toLocaleString(),
});
}
return response;
}
helpers.generateError = (statusCode, message) => { helpers.generateError = (statusCode, message) => {
var payload = { var payload = {
status: { status: {

Loading…
Cancel
Save