refs #5878 feat: use back/locale

This commit is contained in:
Javier Segarra 2024-01-02 10:20:47 +01:00
parent 774514f8c7
commit d988851926
3 changed files with 55 additions and 23 deletions

View File

@ -21,7 +21,7 @@ module.exports = function() {
if (validation.validation(err.message)) {
const error = validation.handleError(req);
if (error)
err.message = validation.message(req, error);
err.message = validation.message(error, req);
}
});

View File

@ -17,17 +17,18 @@ fdescribe('Value is not', () => {
const tag = 'provinceFk';
try {
expect(valueIsNot.validation(messageError)).toBeTrue();
expect(valueIsNot.message(i18n, tag)).toEqual('El campo \'Provincia\' no es válido');
const data = {
method: 'POST',
originalUrl: '/api/updateFiscalData',
method: 'PATCH',
originalUrl: '/api/supplier/updateFiscalData',
body: {
[tag]: null
}
},
__: i18n
};
const result = valueIsNot.handleError(data);
expect(result).toEqual(tag);
expect(result.tag).toEqual(tag);
expect(valueIsNot.message(result, i18n)).toEqual('El campo \'provincia\' no es válido');
} catch (error) {
expect(error).toBeDefined();
}
@ -39,7 +40,6 @@ fdescribe('Value is not', () => {
it('sendToSupport endpoint', () => {
try {
expect(valueIsNot.validation(messageError)).toBeTrue();
expect(valueIsNot.message(i18n, tag)).toEqual(`El campo '${tag}' no es válido`);
const data = {
method: 'POST',
originalUrl: '/api/OsTickets/send-to-support?access_token=DEFAULT_TOKEN',
@ -49,7 +49,8 @@ fdescribe('Value is not', () => {
};
const result = valueIsNot.handleError(data);
expect(result).toEqual(tag);
expect(result.tag).toEqual(tag);
expect(valueIsNot.message(tag, i18n)).toEqual(`El campo '${tag}' no es válido`);
} catch (error) {
expect(error).toBeDefined();
}

View File

@ -1,11 +1,26 @@
const SLASH = '/';
const path = require('path');
const glob = require('glob');
const modulesPath = `modules/**/back/locale/**/**.yml`;
const pathResolve = path.resolve(modulesPath);
const modelsLocale = glob.sync(pathResolve, {}).map((f, data) => {
const file = require(f);
const model = f.substring(f.indexOf('modules'), f.indexOf('back') - 1).split(SLASH)[1];
const locale = path.parse(f).base.split('.')[0];
return [keyMap(model, locale), file.columns];
}
);
const mapLocale = new Map(modelsLocale);
module.exports = {
validation: message => String(message).startsWith('Value is not'),
message: ({__: $t}, _tag) =>
$t('Field are invalid', {tag: $t(_tag)}),
handleError: ({method: verb, originalUrl, body}) => {
message: ({tagValue}, {__: $t}) =>
$t('Field are invalid', {tag: tagValue}),
handleError: ({method: verb, originalUrl, body, __: $t}) => {
const {models} = require('vn-loopback/server/server');
let tag = null;
let module = null;
let moduleOriginal = null;
let path = null;
let hasId = false;
try {
@ -13,34 +28,42 @@ module.exports = {
originalUrl = originalUrl.split('?')[0];
originalUrl = originalUrl.split('api/')[1];
[module, ...path] = originalUrl.split('/');
[module, ...path] = originalUrl.split(SLASH);
hasId = path.length > 1;
// let module = url.split('/')[0];
// let [id, path] = url.substring(url.indexOf('/') + 1).split('/');
moduleOriginal = module;
let model = models[module];
// Capitalize
if (!model) {
module = module.charAt(0).toUpperCase() + module.slice(1);
model = models[module];
}
// Singular
if (!model) {
module = module.substring(0, module.length - 1);
model = models[module];
}
if (!model) throw new Error('No matching model found');
const currentMethod = model.sharedClass.methods().find(method => {
const methodMatch = [method.http].flat().find(el => {
const methodMatch = [method.http].flat().filter(el => el.verb === verb.toLowerCase()).find(el => {
let isValid = false;
if (el.verb === verb.toLowerCase()) {
if (hasId)
isValid = el.path.replace(':id', path[0]) === '/' + path.join('/');
isValid = el.path.replace(':id', path[0]) === SLASH + path.join(SLASH);
else
isValid = el.path.endsWith(path[0]);
}
return isValid;
});
if (methodMatch)
return method;
}
);
if (!currentMethod) throw new Error('No matching currentMethod found');
const {accepts} = currentMethod;
for (const [key, value] of Object.entries(body)) {
if (!value) {
tag = key;
break;
}
const accept = accepts.find(acc => acc.arg === key);
if (accept.type !== 'any') {
let isValid = false;
@ -66,19 +89,27 @@ module.exports = {
break;
}
}
if (!value || !isValid) {
if (!isValid) {
tag = key;
break;
}
}
}
return tag;
if (tag) {
const tagValue = mapLocale.get(keyMap(moduleOriginal, $t.getLocale()))[tag];
return {tag, tagValue};
}
} catch (error) {
throw new Error(error);
}
}
};
function keyMap(model, local, connector = '_') {
return `${model}${connector}${local}`;
}
function isJsonString(str) {
try {
let json = JSON.parse(str);