Skip to content

Commit

Permalink
Merge pull request #1819 from hapijs/reach
Browse files Browse the repository at this point in the history
Reduce reach
  • Loading branch information
hueniverse committed May 28, 2019
2 parents 7bea048 + 3f46ddd commit aa2f4d2
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 6 deletions.
11 changes: 5 additions & 6 deletions lib/errors.js
Expand Up @@ -85,13 +85,13 @@ exports.Err = class {

const localized = this.options.language;

format = format || Hoek.reach(localized, this.type) || Hoek.reach(Language.errors, this.type);
format = format || Hoek.reach(localized, this.type) || Language.flat.get(this.type);

if (format === undefined) {
return `Error code "${this.type}" is not defined, your custom type is missing the correct language definition`;
}

let wrapArrays = Hoek.reach(localized, 'messages.wrapArrays');
let wrapArrays = localized && localized.messages && localized.messages.wrapArrays;
if (typeof wrapArrays !== 'boolean') {
wrapArrays = Language.errors.messages.wrapArrays;
}
Expand All @@ -113,12 +113,11 @@ exports.Err = class {
}

if (!hasKey && !skipKey) {
const localizedKey = Hoek.reach(localized, 'key');
if (typeof localizedKey === 'string') {
format = localizedKey + format;
if (typeof localized.key === 'string') {
format = localized.key + format;
}
else {
format = Hoek.reach(Language.errors, 'key') + format;
format = Language.errors.key + format;
}
}

Expand Down
34 changes: 34 additions & 0 deletions lib/language.js
Expand Up @@ -159,3 +159,37 @@ exports.errors = {
map: 'must be one of {{map}}'
}
};


exports.flatten = function (language) {

const flat = new Map();

let nodes = [{ ref: language, path: '' }];
while (nodes.length) {
const next = [];

for (const { ref, path } of nodes) {
for (const key in ref) {
const value = ref[key];
const current = `${path}${path ? '.' : ''}${key}`;

if (value &&
typeof value === 'object') {

next.push({ ref: value, path: current });
}
else {
flat.set(current, value);
}
}
}

nodes = next;
}

return flat;
};


exports.flat = exports.flatten(exports.errors);

0 comments on commit aa2f4d2

Please sign in to comment.