-
Notifications
You must be signed in to change notification settings - Fork 177
Expand file tree
/
Copy pathindex.ts
More file actions
324 lines (284 loc) · 8.62 KB
/
Copy pathindex.ts
File metadata and controls
324 lines (284 loc) · 8.62 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
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import { components } from '@cowprotocol/cms'
import { getCmsClient } from '@cowprotocol/core'
import { PaginationParam } from 'types'
import { isValidCmsSlug, normalizeSearchArticlesInput } from 'util/cmsValidation'
import { toQueryParams } from 'util/queryParams'
import { DEFAULT_PAGE_SIZE, clientAddons } from './config'
import { querySerializer, getPopulateConfig } from './helpers'
type Schemas = components['schemas']
export type Article = Schemas['ArticleListResponseDataItem']
export type ArticleListResponse = {
data: Article[]
meta: {
pagination: {
page: number
pageSize: number
pageCount: number
total: number
}
}
}
export type SharedRichTextComponent = Schemas['SharedRichTextComponent']
export type Category = Schemas['CategoryListResponseDataItem']
const SKIP_CMS_FETCH_DURING_BUILD =
process.env.NEXT_PHASE === 'phase-production-build' || process.env.SKIP_COW_FI_CMS_FETCH === 'true'
function handleCmsBuildFailure<T>(operation: string, error: unknown, fallback: T): T {
if (SKIP_CMS_FETCH_DURING_BUILD) {
console.error(`[cow-fi] ${operation} failed during build. Skipping CMS fetch.`, error)
return fallback
}
throw error
}
/**
* Open API Fetch client. See docs for usage https://openapi-ts.pages.dev/openapi-fetch/
*/
export const client = getCmsClient()
/**
* Returns all article slugs.
*
* @returns Slugs
*/
export async function getAllArticleSlugs(): Promise<string[]> {
try {
const { data, error, response } = await client.GET('/articles', {
params: {
query: {
fields: ['slug'],
'pagination[pageSize]': DEFAULT_PAGE_SIZE,
},
},
querySerializer,
...clientAddons,
})
if (error) {
console.error(`Error ${response.status} getting article slugs: ${response.url}`, error)
throw error
}
return data.data
.filter((article: Article) => article.attributes)
.map((article: Article) => article.attributes!.slug)
} catch (error) {
return handleCmsBuildFailure('getAllArticleSlugs', error, [])
}
}
/**
* Get categories with images.
*
* @returns Categories with their associated images
*/
export async function getCategories(): Promise<Category[]> {
try {
const { data, error, response } = await client.GET('/categories?populate=*', {
params: {
pagination: {
page: 0,
pageSize: DEFAULT_PAGE_SIZE,
},
sort: 'name:asc',
},
...clientAddons,
})
if (error) {
console.error(`Error ${response.status} getting categories: ${response.url}`, error)
throw error
}
return data.data
} catch (err) {
console.error('An unexpected error occurred:', err)
return handleCmsBuildFailure('getCategories', err, [])
}
}
/**
* Returns all category slugs.
*
* @returns Slugs
*/
export async function getAllCategorySlugs(): Promise<string[]> {
const categories = await getCategories()
return categories.map((category) => category.attributes!.slug!)
}
/**
* Get articles sorted by descending published date.
*
* @returns Articles for the given page
*/
export async function getArticles({
page = 0,
pageSize = DEFAULT_PAGE_SIZE,
filters = {},
}: PaginationParam & { filters?: Record<string, unknown> } = {}): Promise<ArticleListResponse> {
try {
const { data, error, response } = await client.GET('/articles', {
params: {
query: {
'populate[0]': 'cover',
'populate[1]': 'blocks',
'populate[2]': 'seo',
'populate[3]': 'authorsBio',
'pagination[page]': page,
'pagination[pageSize]': pageSize,
sort: 'publishDate:desc,publishedAt:desc',
filters,
},
},
querySerializer,
...clientAddons,
})
if (error) {
console.error(`Error ${response.status} getting articles: ${response.url}. Page ${page}`, error)
throw error
}
return { data: data.data, meta: data.meta }
} catch (error) {
return handleCmsBuildFailure('getArticles', error, {
data: [],
meta: {
pagination: {
page,
pageSize,
pageCount: 0,
total: 0,
},
},
})
}
}
/**
* Search for articles containing a search term across multiple fields.
* Uses Strapi's filtering capabilities to perform the search server-side.
*
* @param searchTerm The term to search for
* @param page The page number (0-indexed)
* @param pageSize The number of articles per page
* @returns Articles matching the search term with pagination info
*/
export async function searchArticles({
searchTerm,
page = 0,
pageSize = DEFAULT_PAGE_SIZE,
}: {
searchTerm: string
page?: number
pageSize?: number
}): Promise<ArticleListResponse> {
const {
searchTerm: trimmedSearchTerm,
page: normalizedPage,
pageSize: normalizedPageSize,
} = normalizeSearchArticlesInput({ searchTerm, page, pageSize })
if (!trimmedSearchTerm) {
return {
data: [],
meta: { pagination: { page: normalizedPage, pageSize: normalizedPageSize, pageCount: 0, total: 0 } },
}
}
try {
const queryParams = {
filters: {
$or: [
{ title: { $startsWithi: trimmedSearchTerm } },
{ title: { $containsi: trimmedSearchTerm } },
{ description: { $containsi: trimmedSearchTerm } },
],
},
pagination: {
page: normalizedPage,
pageSize: normalizedPageSize,
},
sort: ['title:asc'],
populate: ['cover', 'blocks', 'seo', 'authorsBio'],
publicationState: 'live', // Ensure published content
}
const { data, error, response } = await client.GET('/articles', {
params: {
query: toQueryParams(queryParams),
},
...clientAddons,
})
if (error) {
console.error(`Search failed (${response.status}):`, error)
throw new Error(`Search failed: ${error.message}`)
}
return { data: data.data, meta: data.meta }
} catch (error) {
console.error('Search error:', error)
throw new Error('Unable to complete search. Please try again.')
}
}
/**
* Get article by slug.
*
* @param slug Slug of the article
*
* @throws Error if slug is not found
* @throws Error if multiple articles are found with the same slug
*
* @returns Article with the given slug
*/
export async function getArticleBySlug(slug: string): Promise<Article | null> {
if (!slug) throw new Error('Article slug is required') // Fail fast - no silent failures per CMS architecture
try {
const result = await getBySlugAux(slug, '/articles')
return result
} catch (error) {
console.error(`Error getting article by slug ${slug}:`, error)
throw error
}
}
/**
* Get category by slug.
*
* @param slug Slug of the category
*
* @throws Error if slug is not found
* @throws Error if multiple categories are found with the same slug
*
* @returns Category with the given slug
*/
export async function getCategoryBySlug(slug: string): Promise<Category | null> {
return getBySlugAux(slug, '/categories')
}
export type Page = Schemas['PageListResponseDataItem']
/**
* Get page by slug.
*
* @param slug Slug of the page
*
* @throws Error if slug is not found
* @throws Error if multiple pages are found with the same slug
*
* @returns Page with the given slug
*/
export async function getPageBySlug(slug: string): Promise<Page | null> {
return getBySlugAux(slug, '/pages')
}
async function getBySlugAux(slug: string, endpoint: '/articles'): Promise<Article | null>
async function getBySlugAux(slug: string, endpoint: '/categories'): Promise<Category | null>
async function getBySlugAux(slug: string, endpoint: '/pages'): Promise<Page | null>
async function getBySlugAux(slug: string, endpoint: '/categories' | '/articles' | '/pages'): Promise<unknown | null> {
if (!slug) throw new Error('Slug is required') // Fail fast - no silent failures per CMS architecture
if (!isValidCmsSlug(slug)) return null
try {
const entity = endpoint.slice(1, -1)
const populate = getPopulateConfig(endpoint)
const queryParams = {
filters: { slug: { $eq: slug } },
pagination: { page: 1, pageSize: 2 },
populate,
}
const { data, error } = await client.GET(endpoint, {
params: { query: toQueryParams(queryParams) },
...clientAddons,
})
if (error) {
console.error(`Error getting slug ${slug} for ${entity}`, error)
throw error
}
const { total } = data.meta.pagination
if (total === 0) return null
if (total > 1) throw new Error(`Multiple ${entity} found with slug ${slug}`)
return data.data[0]
} catch (error) {
return handleCmsBuildFailure(`getBySlugAux(${endpoint}, ${slug})`, error, null)
}
}