fix: middleware i18n localization.

This commit is contained in:
a.bouhuolia
2021-08-07 08:08:29 +02:00
parent 34377c8e53
commit 0ab4596836
9 changed files with 143 additions and 67 deletions

View File

@@ -1,7 +1,7 @@
import { Response, Request, NextFunction } from 'express';
import { matchedData, validationResult } from 'express-validator';
import accepts from 'accepts';
import { camelCase, snakeCase, omit, set, get } from 'lodash';
import { isArray, drop, first, camelCase, snakeCase, omit, set, get } from 'lodash';
import { mapKeysDeep } from 'utils';
import asyncMiddleware from 'api/middleware/asyncMiddleware';
@@ -57,6 +57,37 @@ export default class BaseController {
next();
}
/**
* Sets localization to response object by the given path.
* @param {Response} response -
* @param {string} path -
* @param {Request} req -
*/
private setLocalizationByPath(
response: any,
path: string,
req: Request,
) {
const DOT = '.';
if (isArray(response)) {
response.forEach((va) => {
const currentPath = first(path.split(DOT));
const value = get(va, currentPath);
if (isArray(value)) {
const nextPath = drop(path.split(DOT)).join(DOT);
this.setLocalizationByPath(value, nextPath, req);
} else {
set(va, path, req.__(value));
}
})
} else {
const value = get(response, path);
set(response, path, req.__(value));
}
}
/**
* Transform the given data to response.
* @param {any} data
@@ -74,13 +105,14 @@ export default class BaseController {
: [translatable];
translatables.forEach((path) => {
const value = get(response, path);
set(response, path, req.__(value));
this.setLocalizationByPath(response, path, req);
});
}
return response;
}
/**
* Async middleware.
* @param {function} callback

View File

@@ -37,9 +37,9 @@ export default class ViewsController extends BaseController {
/**
* List all views that associated with the given resource.
* @param {Request} req -
* @param {Response} res -
* @param {NextFunction} next -
* @param {Request} req - Request object.
* @param {Response} res - Response object.
* @param {NextFunction} next - Next function.
*/
async listResourceViews(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req;
@@ -50,8 +50,9 @@ export default class ViewsController extends BaseController {
tenantId,
resourceModel
);
return res.status(200).send({ views });
return res.status(200).send({
views: this.transfromToResponse(views, ['name', 'columns.label'], req),
});
} catch (error) {
next(error);
}