-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgatsby-node.js
More file actions
107 lines (102 loc) · 2.8 KB
/
Copy pathgatsby-node.js
File metadata and controls
107 lines (102 loc) · 2.8 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
const getPageParent = async (page, context) => {
return await context.nodeModel.findOne({
type: "ContentfulPage",
query: {
filter: {
subpages: { elemMatch: { id: { eq: page.id } } },
id: { ne: page.id },
},
},
});
};
const getBlockParent = async (block, context) => {
const garden = await context.nodeModel.findOne({
type: "ContentfulGarden",
query: {
filter: {
block: { id: { eq: block.id } },
},
},
});
if (garden) {
console.log(`BUILDING GARDEN: ${JSON.stringify(garden.streetAddress)}`);
const page = await context.nodeModel.findOne({
type: "ContentfulPage",
query: {
filter: {
slug: { eq: "gardens" },
},
},
});
if (page) return page;
else console.log(`NO PAGE FOUND FOR ${garden.streetAddress}`);
}
return await context.nodeModel.findOne({
type: "ContentfulPage",
query: {
filter: {
blocks: { elemMatch: { id: { eq: block.id } } },
},
},
});
};
const buildBlockURL = async (block, context) => {
let p = await getBlockParent(block, context);
const c = [block.slug];
while (p) {
c.push(p.slug);
p = await getPageParent(p, context);
}
return `/${c.reverse().join("/")}`;
};
exports.createResolvers = ({ createResolvers }) => {
const resolvers = {
ContentfulBlock: {
url: {
type: "String",
resolve: (source, args, context, info) => {
return buildBlockURL(source, context);
},
},
pageLineage: {
type: "[ContentfulPage]",
resolve: async (source, args, context, info) => {
const firstParent = await getBlockParent(source, context);
if (!firstParent) return [];
const lineage = [firstParent];
let hasParent = true;
while (hasParent) {
const p = await getPageParent(lineage[lineage.length - 1], context);
hasParent = !!p;
if (p) {
lineage.push(p);
}
}
return lineage;
},
},
cousinPages: {
type: "[ContentfulPage]",
resolve: async (source, args, context, info) => {
const firstParent = await getBlockParent(source, context);
if (!firstParent) return [];
let greatestGrandParent = firstParent;
let hasParent = true;
while (hasParent) {
const p = await getPageParent(greatestGrandParent, context);
hasParent = !!p;
if (p) {
greatestGrandParent = p;
}
}
const ids = greatestGrandParent.subpages___NODE || [];
return await context.nodeModel.getNodesByIds({
ids,
type: "ContentfulPage",
});
},
},
},
};
createResolvers(resolvers);
};