This repository has been archived by the owner on May 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
isValidTranslationsObject.js
79 lines (69 loc) · 2.54 KB
/
isValidTranslationsObject.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const { differenceWith, isEqual, isPlainObject, isEmpty } = require("lodash");
const getTranslationParameters = require("./getTranslationParameters");
const isValidTranslationsObject = (translationsObject) => {
if (!isPlainObject(translationsObject)) {
throw new TypeError("translationsObject must be an object.");
}
if (isEmpty(translationsObject)) {
throw new TypeError("translationsObject must not be an empty object.");
}
// Let's start validation by looping over translationObject entries
for (let [translationKey, translationValue] of Object.entries(
translationsObject
)) {
// Get translation parameters for the string that needs to be translated
const translationKeyParameters = getTranslationParameters(translationKey);
// Check if the translation is a simple string
if (typeof translationValue === "string") {
// Get translation parameters for translation
const translationValueParameters = getTranslationParameters(
translationValue
);
// Check if we have all parameters
// from the string that needs translated in translation string
if (
differenceWith(
translationKeyParameters,
translationValueParameters,
isEqual
).length !== 0
) {
// Not a valid translation
// Return early, no need to continue
return false;
}
}
// Check if the translation is using context
if (isPlainObject(translationValue)) {
// Check if the translation contains default context in keys
if (!Object.keys(translationValue).includes("default")) {
// Not a valid translation
// Return early, no need to continue
return false;
}
// Loop over translation contexts
for (let translationContext of Object.values(translationValue)) {
const translationValueParameters = getTranslationParameters(
translationContext
);
// Check if we have all parameters
// from the string that needs translated in translation string
// TODO: A little bit WET (not DRY), right? See above ^
// Refactor into a function, something like compareTranslationParameters
if (
differenceWith(
translationKeyParameters,
translationValueParameters,
isEqual
).length !== 0
) {
// Not a valid translation
// Return early, no need to continue
return false;
}
}
}
}
return true;
};
module.exports = isValidTranslationsObject;