-
Notifications
You must be signed in to change notification settings - Fork 12
/
import-data.js
89 lines (80 loc) · 2.24 KB
/
import-data.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
import Reindex from 'reindex-js';
import data from './data/json';
const reindex = new Reindex(process.env.REINDEX_URL);
reindex.setToken(process.env.REINDEX_TOKEN);
function createMutation(name) {
const lowerName = name.toLowerCase();
return `
mutation Import${name}(\$${lowerName}: _Create${name}Input!) {
create${name}(input: \$${lowerName}) {
id
}
}`;
}
function path(obj, path) {
try {
return eval('obj.' + path);
} catch(e) {
console.log('pathing error', e);
return undefined;
}
}
function resolveRefs(item) {
const refs = {};
Object.keys(item).forEach((key) => {
if (typeof item[key] !== 'string') {
return;
}
if (item[key].indexOf('$ref') === 0) {
const ref = item[key].match(/\(([^)]+)\)/)[1];
refs[key] = path(data, ref).id
}
});
return {
...item,
...refs
};
}
async function importEntity(entity, mutation, mutationKey) {
for (const idx in data[entity]) {
const item = data[entity][idx];
const solvedItem = resolveRefs(item);
console.log(solvedItem);
try {
const result = await reindex.query(mutation, { [mutationKey]: solvedItem });
if (typeof result.errors !== 'undefined') {
console.log(result.errors);
throw "mutation error";
}
const firstKey = Object.keys(result.data)[0];
data[entity][idx].id = result.data[firstKey].id;
console.log('created ' + mutationKey + ': ' + result.data[firstKey].id);
console.log(item);
} catch(e) {
console.log('mutation error', e.stack);
throw e;
}
}
return Promise.resolve({});
}
const createCompany = createMutation('Company');
const createSpeaker = createMutation('Speaker');
const createSponsor = createMutation('Sponsor');
const createEvent = createMutation('Event');
async function doImport() {
try {
await importEntity('companies', createCompany, 'company');
await importEntity('sponsors', createSponsor, 'sponsor');
await importEntity('speakers', createSpeaker, 'speaker');
await importEntity('events', createEvent, 'event');
} catch(e) {
console.log('import error', e.stack);
}
console.log('** done **');
}
console.log('** importing data **');
try {
doImport();
} catch(e) {
console.error(e);
}