-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcb-content-import-translations
executable file
·89 lines (75 loc) · 2.29 KB
/
cb-content-import-translations
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
#!/usr/bin/env node
const contentful = require('contentful-management');
const Papa = require('papaparse');
const fs = require('fs');
const path = require('path');
const { Command } = require('commander');
const { findOrCreateEntry } = require('./utils');
const main = async ({
accessToken = process.env.TOKEN,
spaceId,
environmentId = 'master',
source,
languages,
}) => {
const contentfulClient = await contentful.createClient({ accessToken });
const client = await contentfulClient
.getSpace(spaceId)
.then(s => s.getEnvironment(environmentId))
.catch(console.error);
let jsonData;
const filePath = path.resolve(source);
try {
const csvData = fs.readFileSync(filePath);
jsonData = Papa.parse(String(csvData), { header: true });
} catch (e) {
console.error(e);
process.exit(0);
}
const allowedFields = ['identifier', ...languages];
const dataToImport = jsonData.data.map(field =>
Object.keys(field)
.filter(key => allowedFields.includes(key))
.reduce((obj, key) => {
obj[key] = field[key];
return obj;
}, {})
);
for (let i in dataToImport) {
console.log(`${Number(i) + 1}/${dataToImport.length}`);
const item = dataToImport[i];
const data = { fields: { translation: {} } };
languages.forEach(l => {
data.fields.translation[l] = item[l];
});
let entry = await findOrCreateEntry(
client,
'translation',
item.identifier,
data
);
if (!entry.fields) entry.fields = {};
entry.fields.identifier = { 'en-US': item.identifier };
entry.fields.translation = {
...entry.fields.translation,
...data.fields.translation,
};
const shouldPublish = entry.isPublished();
entry = await entry.update();
if (shouldPublish) await entry.publish();
}
};
const program = new Command();
program
.requiredOption('-t, --accessToken <accessToken>', 'Content Management Token')
.requiredOption('-s, --spaceId <spaceId>', 'Space Id')
.requiredOption('--source <source>', 'CSV source file')
.option('-e, --environmentId <environmentId>', 'Environment Id');
program.parseAsync(process.argv);
main({
accessToken: program.accessToken,
spaceId: program.spaceId,
source: program.source,
environmentId: program.environmentId,
languages: program.args,
});