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)) { if (validation.validation(err.message)) {
const error = validation.handleError(req); const error = validation.handleError(req);
if (error) 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'; const tag = 'provinceFk';
try { try {
expect(valueIsNot.validation(messageError)).toBeTrue(); expect(valueIsNot.validation(messageError)).toBeTrue();
expect(valueIsNot.message(i18n, tag)).toEqual('El campo \'Provincia\' no es válido');
const data = { const data = {
method: 'POST', method: 'PATCH',
originalUrl: '/api/updateFiscalData', originalUrl: '/api/supplier/updateFiscalData',
body: { body: {
[tag]: null [tag]: null
} },
__: i18n
}; };
const result = valueIsNot.handleError(data); 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) { } catch (error) {
expect(error).toBeDefined(); expect(error).toBeDefined();
} }
@ -39,7 +40,6 @@ fdescribe('Value is not', () => {
it('sendToSupport endpoint', () => { it('sendToSupport endpoint', () => {
try { try {
expect(valueIsNot.validation(messageError)).toBeTrue(); expect(valueIsNot.validation(messageError)).toBeTrue();
expect(valueIsNot.message(i18n, tag)).toEqual(`El campo '${tag}' no es válido`);
const data = { const data = {
method: 'POST', method: 'POST',
originalUrl: '/api/OsTickets/send-to-support?access_token=DEFAULT_TOKEN', originalUrl: '/api/OsTickets/send-to-support?access_token=DEFAULT_TOKEN',
@ -49,7 +49,8 @@ fdescribe('Value is not', () => {
}; };
const result = valueIsNot.handleError(data); 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) { } catch (error) {
expect(error).toBeDefined(); 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 = { module.exports = {
validation: message => String(message).startsWith('Value is not'), validation: message => String(message).startsWith('Value is not'),
message: ({__: $t}, _tag) => message: ({tagValue}, {__: $t}) =>
$t('Field are invalid', {tag: $t(_tag)}), $t('Field are invalid', {tag: tagValue}),
handleError: ({method: verb, originalUrl, body}) => { handleError: ({method: verb, originalUrl, body, __: $t}) => {
const {models} = require('vn-loopback/server/server'); const {models} = require('vn-loopback/server/server');
let tag = null; let tag = null;
let module = null; let module = null;
let moduleOriginal = null;
let path = null; let path = null;
let hasId = false; let hasId = false;
try { try {
@ -13,34 +28,42 @@ module.exports = {
originalUrl = originalUrl.split('?')[0]; originalUrl = originalUrl.split('?')[0];
originalUrl = originalUrl.split('api/')[1]; originalUrl = originalUrl.split('api/')[1];
[module, ...path] = originalUrl.split('/'); [module, ...path] = originalUrl.split(SLASH);
hasId = path.length > 1; hasId = path.length > 1;
// let module = url.split('/')[0];
// let [id, path] = url.substring(url.indexOf('/') + 1).split('/');
moduleOriginal = module;
let model = models[module]; let model = models[module];
// Capitalize
if (!model) {
module = module.charAt(0).toUpperCase() + module.slice(1);
model = models[module];
}
// Singular
if (!model) { if (!model) {
module = module.substring(0, module.length - 1); module = module.substring(0, module.length - 1);
model = models[module]; model = models[module];
} }
if (!model) throw new Error('No matching model found'); if (!model) throw new Error('No matching model found');
const currentMethod = model.sharedClass.methods().find(method => { 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; let isValid = false;
if (el.verb === verb.toLowerCase()) {
if (hasId) if (hasId)
isValid = el.path.replace(':id', path[0]) === '/' + path.join('/'); isValid = el.path.replace(':id', path[0]) === SLASH + path.join(SLASH);
else else
isValid = el.path.endsWith(path[0]); isValid = el.path.endsWith(path[0]);
}
return isValid; return isValid;
}); });
if (methodMatch) if (methodMatch)
return method; return method;
} }
); );
if (!currentMethod) throw new Error('No matching currentMethod found');
const {accepts} = currentMethod; const {accepts} = currentMethod;
for (const [key, value] of Object.entries(body)) { for (const [key, value] of Object.entries(body)) {
if (!value) {
tag = key;
break;
}
const accept = accepts.find(acc => acc.arg === key); const accept = accepts.find(acc => acc.arg === key);
if (accept.type !== 'any') { if (accept.type !== 'any') {
let isValid = false; let isValid = false;
@ -66,19 +89,27 @@ module.exports = {
break; break;
} }
} }
if (!value || !isValid) { if (!isValid) {
tag = key; tag = key;
break; break;
} }
} }
} }
return tag; if (tag) {
const tagValue = mapLocale.get(keyMap(moduleOriginal, $t.getLocale()))[tag];
return {tag, tagValue};
}
} catch (error) { } catch (error) {
throw new Error(error); throw new Error(error);
} }
} }
}; };
function keyMap(model, local, connector = '_') {
return `${model}${connector}${local}`;
}
function isJsonString(str) { function isJsonString(str) {
try { try {
let json = JSON.parse(str); let json = JSON.parse(str);