-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupsertEntries.js
More file actions
71 lines (68 loc) · 1.97 KB
/
upsertEntries.js
File metadata and controls
71 lines (68 loc) · 1.97 KB
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
const contentful = require('contentful-management');
const client = contentful.createClient({
accessToken: process.env.MANAGEMENT_TOKEN
});
module.exports = (updatedEntries, newEntries) => {
const promises = [];
if (updatedEntries.length) {
promises.push(updateEntries(updatedEntries));
}
if (newEntries.length) {
promises.push(createEntries(newEntries));
}
const flattenedPromises = [].concat.apply([], promises);
return Promise.all(flattenedPromises)
}
const createEntries = (newEntries) => {
console.log('Creating new entries...');
console.log(newEntries);
return client.getSpace(process.env.TARGET_SPACE_ID)
.then( (space) => {
return newEntries.map( (entry) => {
return space.createEntryWithId(entry.sys.contentType.sys.id, entry.sys.id, entry)
.then( (createdEntry) => {
return createdEntry.publish();
})
.catch( (err) => {
console.error('Issue creating entry!');
console.log(entry)
console.error(err);
throw new Error(err);
});
});
})
.catch( (err) => {
console.log('Something went wrong...');
console.error(err);
throw new Error(err)
});
}
const updateEntries = (updatedEntries) => {
console.log('Updating entries...');
console.log(updatedEntries);
return client.getSpace(process.env.TARGET_SPACE_ID)
.then( (space) => {
return updatedEntries.map( (entry) => {
return space.getEntry(entry.sys.id)
.then( (foundEntry) => {
// merge found entry and exist entry and save
delete entry.sys
foundEntry = Object.assign(foundEntry, entry);
return foundEntry.update();
})
.then( (updatedEntry) => {
updatedEntry.publish();
})
.catch( (err) => {
console.error('Issue updating entry');
console.log(entry)
console.error(err);
throw new Error(err);
});
});
})
.catch( (err) => {
console.error('Something bad happened');
console.error(err);
});
}