-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathv4_using_preparation_data.js
More file actions
81 lines (65 loc) · 2.08 KB
/
Copy pathv4_using_preparation_data.js
File metadata and controls
81 lines (65 loc) · 2.08 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
72
73
74
75
76
77
78
79
80
81
// Adding a new field "hasWikiPage"
// "hasWikiPage" is a boolean field that is set to true if the item has a wiki page
// It is calculated with a prepare function that fetches the wiki page status for each item
const { utils } = require('dynamo-data-transform');
const userAgentHeader = {
'User-Agent': 'Chrome/81.0.4044.138',
};
const fetch = (...args) => import('node-fetch').then(({ default: nodeFetch }) => nodeFetch(
...args,
{
headers: userAgentHeader,
},
));
const TABLE_NAME = 'UsersExample';
const transformUp = async ({ ddb, preparationData, isDryRun }) => {
const addHasWikiPage = (hasWikiDict) => (item) => {
const valueFromPreparation = hasWikiDict[`${item.PK}-${item.SK}`];
const updatedItem = valueFromPreparation ? {
...item,
hasWikiPage: valueFromPreparation,
} : item;
return updatedItem;
};
return utils.transformItems(
ddb,
TABLE_NAME,
addHasWikiPage(JSON.parse(preparationData)),
isDryRun,
);
};
const transformDown = async ({ ddb, isDryRun }) => {
const removeHasWikiPage = (item) => {
const { hasWikiPage, ...oldItem } = item;
return oldItem;
};
return utils.transformItems(ddb, TABLE_NAME, removeHasWikiPage, isDryRun);
};
const prepare = async ({ ddb }) => {
let lastEvalKey;
let preparationData = {};
let scannedAllItems = false;
while (!scannedAllItems) {
const { Items, LastEvaluatedKey } = await utils.getItems(ddb, lastEvalKey, TABLE_NAME);
lastEvalKey = LastEvaluatedKey;
const currentPreparationData = await Promise.all(Items.map(async (item) => {
const wikiItemUrl = `https://en.wikipedia.org/wiki/${item.name}`;
const currWikiResponse = await fetch(wikiItemUrl);
return {
[`${item.PK}-${item.SK}`]: currWikiResponse.status === 200,
};
}));
preparationData = {
...preparationData,
...currentPreparationData.reduce((acc, item) => ({ ...acc, ...item }), {}),
};
scannedAllItems = !lastEvalKey;
}
return preparationData;
};
module.exports = {
transformUp,
transformDown,
prepare,
transformationNumber: 4,
};