-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgql-queries.tsx
181 lines (159 loc) · 5.88 KB
/
gql-queries.tsx
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import {
AllNodesQuery,
AllNodesQueryVariables,
ConfigPagesQuery,
ConfigPagesUnion,
MenuAvailable,
MenuItem,
NodeUnion,
RouteQuery,
RouteRedirect,
StanfordBasicSiteSetting,
} from "@lib/gql/__generated__/drupal.d"
import {graphqlClient} from "@lib/gql/gql-client"
import {unstable_cache as nextCache} from "next/cache"
import {ClientError} from "graphql-request"
import {GraphQLError} from "graphql/error"
type DrupalGraphqlError = GraphQLError & {debugMessage: string}
export const getEntityFromPath = async <T extends NodeUnion>(
path: string,
previewMode?: boolean,
teaser?: boolean
): Promise<{
entity?: T
redirect?: RouteRedirect["url"]
}> => {
const getData = nextCache(
async () => {
// Paths that start with /node/ should not be used.
if (path.startsWith("/node/")) return {}
let query: RouteQuery
try {
query = await graphqlClient(undefined, previewMode).Route({
path,
teaser: !!teaser,
})
} catch (e) {
if (e instanceof ClientError) {
// @ts-expect-error Client error type doesn't define the debugMessage, but it's there.
const messages = e.response.errors?.map((error: DrupalGraphqlError) => error.debugMessage || error.message)
console.warn([...new Set(messages)].join(" "))
} else {
console.warn(e instanceof Error ? e.message : "An error occurred")
}
return {}
}
if (query.route?.__typename === "RouteRedirect") return {redirect: query.route.url}
const entity: T | undefined =
query.route?.__typename === "RouteInternal" && query.route.entity ? (query.route.entity as T) : undefined
return {entity}
},
[path, previewMode ? "preview" : "anonymous", teaser ? "teaser" : "full"],
{tags: ["all-entities", `paths:${path}`]}
)
return getData()
}
export const getConfigPage = nextCache(
async <T extends ConfigPagesUnion>(configPageType: ConfigPagesUnion["__typename"]): Promise<T | undefined> => {
let query: ConfigPagesQuery
try {
query = await graphqlClient().ConfigPages()
} catch (e) {
console.warn("Unable to fetch config pages: " + (e instanceof Error && e.stack))
return
}
const queryKeys = Object.keys(query) as (keyof ConfigPagesQuery)[]
for (let i = 0; i < queryKeys.length; i++) {
const queryKey = queryKeys[i]
if (queryKey !== "__typename" && query[queryKey]?.nodes[0]?.__typename === configPageType) {
return query[queryKey].nodes[0] as T
}
}
},
[],
{tags: ["config-pages"]}
)
export const getConfigPageField = nextCache(
async <T extends ConfigPagesUnion, F>(
configPageType: ConfigPagesUnion["__typename"],
fieldName: keyof T
): Promise<F | undefined> => {
const configPage = await getConfigPage<T>(configPageType)
return configPage?.[fieldName] as F
},
[],
{tags: ["config-pages"]}
)
export const getMenu = async (name?: MenuAvailable, maxLevels?: number): Promise<MenuItem[]> => {
const menuName = name?.toLowerCase() || "main"
const getData = nextCache(
async () => {
const menu = await graphqlClient().Menu({name})
const menuItems = (menu.menu?.items || []) as MenuItem[]
const filterInaccessible = (items: MenuItem[], level: number): MenuItem[] => {
if (maxLevels && level > maxLevels) return []
items = items.filter(item => item.title !== "Inaccessible")
items.map(item => (item.children = filterInaccessible(item.children, level + 1)))
return items
}
return filterInaccessible(menuItems, 0)
},
["menus", menuName, maxLevels?.toString() || "all"],
{tags: ["menus", `menu:${menuName}`]}
)
return getData()
}
export const getAllNodes = nextCache(
async () => {
const nodes: NodeUnion[] = []
let fetchMore = true
let nodeQuery: AllNodesQuery
let queryKeys: (keyof AllNodesQuery)[] = []
const cursors: Omit<AllNodesQueryVariables, "first"> = {}
while (fetchMore) {
nodeQuery = await graphqlClient().AllNodes({first: 1000, ...cursors})
queryKeys = Object.keys(nodeQuery) as (keyof AllNodesQuery)[]
fetchMore = false
queryKeys.map(queryKey => {
if (queryKey === "__typename") return
nodeQuery[queryKey]?.nodes.map(node => nodes.push(node as NodeUnion))
if (nodeQuery[queryKey].pageInfo.endCursor) cursors[queryKey] = nodeQuery[queryKey].pageInfo.endCursor
if (nodeQuery[queryKey].pageInfo.hasNextPage) fetchMore = true
})
}
return nodes
},
["all-nodes"],
{revalidate: 604800, tags: ["all-entities"]}
)
/**
* If environment variables are available, return those. If not, fetch from the config page.
*/
export const getAlgoliaCredential = nextCache(
async () => {
if (process.env.ALGOLIA_ID && process.env.ALGOLIA_INDEX && process.env.ALGOLIA_KEY) {
return [process.env.ALGOLIA_ID, process.env.ALGOLIA_INDEX, process.env.ALGOLIA_KEY]
}
const useAlgolia = await getConfigPageField<StanfordBasicSiteSetting, StanfordBasicSiteSetting["suSiteAlgoliaUi"]>(
"StanfordBasicSiteSetting",
"suSiteAlgoliaUi"
)
if (!useAlgolia) return []
const appId = await getConfigPageField<StanfordBasicSiteSetting, StanfordBasicSiteSetting["suSiteAlgoliaId"]>(
"StanfordBasicSiteSetting",
"suSiteAlgoliaId"
)
const indexName = await getConfigPageField<
StanfordBasicSiteSetting,
StanfordBasicSiteSetting["suSiteAlgoliaIndex"]
>("StanfordBasicSiteSetting", "suSiteAlgoliaIndex")
const apiKey = await getConfigPageField<StanfordBasicSiteSetting, StanfordBasicSiteSetting["suSiteAlgoliaSearch"]>(
"StanfordBasicSiteSetting",
"suSiteAlgoliaSearch"
)
if (appId) console.warn("It is recommended to set environment variables for Algolia credentials.")
return appId && indexName && apiKey ? [appId, indexName, apiKey] : []
},
["algolia"],
{tags: ["algolia", "config-pages"]}
)