-
-
Notifications
You must be signed in to change notification settings - Fork 39
/
update-taxonomy-suggestions.js
128 lines (118 loc) · 2.76 KB
/
update-taxonomy-suggestions.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
const fs = require("fs");
const axios = require("axios");
// Map locale folder name to the name used in the OFF api
const taxonomyURLfileName = {
category: "categories",
packaging: "packagings",
label: "labels",
};
const LANG = ["en", "de", "es", "fr", "hr", "nl", "sv"];
const LETTERS = [
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
];
const cleanName = (name) =>
name
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase()
.replace(/[^0-9a-z]/gi, "-");
const isMatching = (prefix) => (name) =>
cleanName(name)
.split("-")
.some((subString) => subString.startsWith(prefix));
Object.keys(taxonomyURLfileName).forEach(async (taxonomyType) => {
const { data } = await axios.get(
`https://static.openfoodfacts.org/data/taxonomies/${taxonomyURLfileName[taxonomyType]}.full.json`,
);
LANG.forEach((lang) => {
const saveFile = (prefix, data) => {
const destFile = `./public/data/${lang}/${taxonomyType}/${prefix}.json`;
const stringify = JSON.stringify(data, null, 2);
fs.writeFileSync(destFile, stringify);
};
const exportedData = Object.keys(data).flatMap((key) => {
const name = data[key]?.name?.[lang] ?? data[key]?.name?.en ?? null;
return name ? [{ key, name }] : [];
});
exportedData.sort((a, b) => a.name.localeCompare(b.name));
let fileNb = 0;
console.log(`${taxonomyType}.${lang}`);
LETTERS.forEach((l1) => {
const prefix = `${l1}`;
const solutions1 = exportedData.filter(({ name }) =>
isMatching(prefix)(name),
);
if (solutions1.length === 0) {
return;
}
if (solutions1.length < 100) {
saveFile(prefix, solutions1);
fileNb += 1;
return;
}
saveFile(prefix, solutions1.slice(0, 10));
LETTERS.forEach((l2) => {
const prefix = `${l1}${l2}`;
const solutions2 = solutions1.filter(({ name }) =>
isMatching(prefix)(name),
);
if (solutions2.length === 0) {
return;
}
if (solutions2.length < 100) {
saveFile(prefix, solutions2);
fileNb += 1;
return;
}
saveFile(prefix, solutions2.slice(0, 10));
LETTERS.forEach((l3) => {
const prefix = `${l1}${l2}${l3}`;
const solutions3 = solutions2.filter(({ name }) =>
isMatching(prefix)(name),
);
if (solutions3.length === 0) {
return;
}
saveFile(prefix, solutions3);
fileNb += 1;
});
});
});
console.log(fileNb);
});
});