-
Notifications
You must be signed in to change notification settings - Fork 5
/
merge-query.js
67 lines (56 loc) · 1.88 KB
/
merge-query.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
import {get, set} from "lodash/fp";
import deepmerge from "deepmerge";
import {envelope as env, utils} from "@sugarcube/core";
const plugin = (envelope, {cfg, log}) => {
const overwrite = get("workflow.overwrite_query_merge", cfg);
const fields = utils.sToA(",", get("workflow.merge_query_fields", cfg));
if (fields.length === 0) {
log.info("No query fields are configured to be merged. Skipping.");
return envelope;
}
log.info(
`Merging the following fields from the query into the unit: ${fields.join(
", ",
)}`,
);
return env.fmapData(
unit =>
unit._sc_queries.reduce((memo, query) => {
const toMerge = fields.reduce((acc, field) => {
const oldValue = get(field, unit);
const newValue = get(field, query);
if (!overwrite && oldValue != null) {
log.info(
`Not overwriting ${oldValue} with ${newValue} for field ${field} in ${query.type}/${unit._sc_id_hash}`,
);
return acc;
}
if (overwrite && oldValue != null) {
log.info(
`Overwriting ${oldValue} with ${newValue} for field ${field} in ${query.type}/${unit._sc_id_hash}`,
);
} else {
log.info(
`Merging ${newValue} for field ${field} in ${query.type}/${unit._sc_id_hash}`,
);
}
return deepmerge(acc, set(field, newValue, {}));
}, {});
return deepmerge(memo, toMerge);
}, unit),
envelope,
);
};
plugin.argv = {
"workflow.merge_query_fields": {
type: "string",
desc: "List the query fields to merge into the unit.",
},
"workflow.overwrite_query_merge": {
type: "boolean",
desc: "Overwrite unit values with query values when merging.",
default: false,
},
};
plugin.desc = "Merge fields from the query object into the unit.";
export default plugin;