forked from vercel/commerce
-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.ts
338 lines (292 loc) · 10.7 KB
/
index.ts
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import { headers } from 'next/headers';
import { NextRequest, NextResponse } from 'next/server';
import { revalidateTag } from 'next/cache';
import { TAGS } from 'lib/constants';
import {
requestCategory,
requestCategoryList,
requestCategoryProductsCollection,
requestCrossSell,
requestNavigation,
requestProductsCollection,
requestSearchCollectionProducts,
requestSeoUrl,
requestSeoUrls
} from './api';
import { ExtendedCategory, ExtendedProduct, ExtendedProductListingResult } from './api-extended';
import {
getDefaultCategoryCriteria,
getDefaultCategoryWithCmsCriteria,
getDefaultCrossSellingCriteria,
getDefaultProductCriteria,
getDefaultProductsCriteria,
getDefaultSearchProductsCriteria,
getDefaultSubCategoriesCriteria,
getSeoUrlCriteria,
getSortingCriteria
} from './criteria';
import {
transformCollection,
transformHandle,
transformMenu,
transformPage,
transformProduct,
transformProducts,
transformSubCollection
} from './transform';
import {
ApiSchemas,
CategoryListingResultSW,
Menu,
Page,
Product,
ProductListingCriteria,
StoreNavigationTypeSW
} from './types';
import { isSeoUrls } from 'lib/shopware/helpers';
export async function getMenu(params?: {
type?: StoreNavigationTypeSW;
depth?: number;
}): Promise<Menu[]> {
const type = params?.type || 'main-navigation';
const depth = params?.depth || 1;
const res = await requestNavigation(type, depth);
return res ? transformMenu(res, type) : [];
}
export async function getPage(handle: string | []): Promise<Page | undefined> {
let seoUrlElement;
let pageIdOrHandle = decodeURIComponent(transformHandle(handle)).replace('cms/', '');
if (pageIdOrHandle === '') {
return undefined;
}
if (isSeoUrls()) {
seoUrlElement = await getFirstSeoUrlElement(pageIdOrHandle);
if (seoUrlElement) {
pageIdOrHandle = seoUrlElement.foreignKey;
}
if (!seoUrlElement) {
console.log('[getPage] Did not found any seoUrl element with page handle:', pageIdOrHandle);
}
}
const category = await getCategory(pageIdOrHandle);
if (!category) {
console.log('[getPage] Did not found any category with handle:', pageIdOrHandle);
}
return category ? transformPage(category, seoUrlElement) : undefined;
}
export async function getFirstSeoUrlElement(
handle: string
): Promise<ApiSchemas['SeoUrl'] | undefined> {
const seoURLCriteria = getSeoUrlCriteria(handle);
const seoURL = await requestSeoUrl(seoURLCriteria);
if (seoURL && seoURL.elements && seoURL.elements.length > 0 && seoURL.elements[0]) {
return seoURL.elements[0];
}
}
export async function getFirstProduct(productId: string): Promise<ExtendedProduct | undefined> {
const productCriteria = getDefaultProductCriteria(productId);
const listing: ExtendedProductListingResult | undefined =
await requestProductsCollection(productCriteria);
if (listing && listing.elements && listing.elements.length > 0 && listing.elements[0]) {
return listing.elements[0];
}
}
// ToDo: should be more dynamic (depending on handle), should work with server and not client see generateStaticParams from next.js
export async function getSubCollections(collection: string) {
const collectionName = decodeURIComponent(transformHandle(collection ?? ''));
let criteria = getDefaultSubCategoriesCriteria(collectionName);
let res: CategoryListingResultSW | undefined = undefined;
const parentCollectionName =
Array.isArray(collection) && collection[0] ? collection[0] : undefined;
if (isSeoUrls()) {
const seoUrlElement = await getFirstSeoUrlElement(collectionName);
if (seoUrlElement) {
criteria = getDefaultSubCategoriesCriteria(seoUrlElement.foreignKey);
}
}
// @ts-ignore
res = await requestCategoryList(criteria);
return res ? transformSubCollection(res, parentCollectionName) : [];
}
export async function getSearchCollectionProducts(params?: {
query?: string;
reverse?: boolean;
sortKey?: string;
categoryId?: string;
defaultSearchCriteria?: Partial<ProductListingCriteria>;
}) {
const searchQuery = params?.query ?? '';
const criteria = getDefaultSearchProductsCriteria(searchQuery);
const sorting = getSortingCriteria(params?.sortKey, params?.reverse);
const searchCriteria = { ...criteria, ...sorting };
const search = await requestSearchCollectionProducts(searchCriteria);
if (isSeoUrls() && search) {
search.elements = await changeVariantUrlToParentUrl(search);
}
return search ? transformProducts(search) : [];
}
export async function changeVariantUrlToParentUrl(
collection: ExtendedProductListingResult
): Promise<ExtendedProduct[]> {
const newElements: ExtendedProduct[] = [];
if (collection.elements && collection.elements.length > 0) {
await Promise.all(
collection.elements.map(async (item) => {
if (item.parentId && item.seoUrls && item.seoUrls[0]) {
const parentProduct = await getFirstProduct(item.parentId);
if (parentProduct && parentProduct.seoUrls && parentProduct.seoUrls[0]) {
item.seoUrls[0].seoPathInfo = parentProduct.seoUrls[0].seoPathInfo;
}
}
newElements.push(item);
})
);
}
return newElements;
}
export async function getCollectionProducts(params?: {
collection: string;
page?: number;
reverse?: boolean;
sortKey?: string;
categoryId?: string;
defaultSearchCriteria?: Partial<ProductListingCriteria>;
}): Promise<{ products: Product[]; total: number; limit: number }> {
let products;
let category = params?.categoryId;
const collectionName = decodeURIComponent(transformHandle(params?.collection ?? ''));
const sorting = getSortingCriteria(params?.sortKey, params?.reverse);
if (isSeoUrls() && !category && collectionName !== '') {
const seoUrlElement = await getFirstSeoUrlElement(collectionName);
if (seoUrlElement) {
category = seoUrlElement.foreignKey;
}
if (!category) {
console.log(
'[useListing][search] Did not found any category with collection name:',
collectionName
);
}
}
if (!isSeoUrls()) {
category = collectionName ?? undefined;
}
if (category) {
const criteria = !params?.defaultSearchCriteria
? getDefaultProductsCriteria(params?.page)
: params?.defaultSearchCriteria;
const productsCriteria = { ...criteria, ...sorting };
products = await requestCategoryProductsCollection(category, productsCriteria);
if (products) {
products.elements = await changeVariantUrlToParentUrl(products);
}
}
return products
? {
products: transformProducts(products),
total: products.total ?? 0,
limit: products.limit ?? 0
}
: { products: [], total: 0, limit: 0 };
}
export async function getCategory(
categoryId: string,
cms: boolean = false
): Promise<ExtendedCategory | undefined> {
const criteria = cms ? getDefaultCategoryWithCmsCriteria() : getDefaultCategoryCriteria();
return await requestCategory(categoryId, criteria);
}
// This function is only used for generateMetadata at app/search/(collection)/[...collection]/page.tsx
export async function getCollection(handle: string | []) {
let path;
let seoUrlElement;
let categoryIdOrHandle = decodeURIComponent(transformHandle(handle));
if (isSeoUrls()) {
seoUrlElement = await getFirstSeoUrlElement(categoryIdOrHandle);
if (seoUrlElement) {
categoryIdOrHandle = seoUrlElement.foreignKey;
path = seoUrlElement.seoPathInfo ?? '';
}
}
const category = await getCategory(categoryIdOrHandle);
if (category) {
const collection = transformCollection(category, seoUrlElement);
path = path ?? category.id ?? '';
return {
...collection,
path: `/search/${path}`
};
}
}
export async function getProductSeoUrls() {
const productSeoUrls: { path: string; updatedAt: string }[] = [];
const seoUrls = await requestSeoUrls('frontend.detail.page');
if (seoUrls && seoUrls.elements && seoUrls.elements.length > 0) {
seoUrls.elements.map((item) =>
productSeoUrls.push({ path: item.seoPathInfo, updatedAt: item.updatedAt ?? item.createdAt })
);
}
return productSeoUrls;
}
export async function getProduct(handle: string | []): Promise<Product | undefined> {
let productSW: ExtendedProduct | undefined;
let productId: string | undefined;
const productHandle = decodeURIComponent(transformHandle(handle));
productId = productHandle; // if we do not use seoUrls the handle should be the product id
if (isSeoUrls()) {
const seoUrlElement = await getFirstSeoUrlElement(productHandle);
if (seoUrlElement) {
productId = seoUrlElement.foreignKey;
}
}
if (!productId) {
console.log('[getProduct][search] Did not found any product with handle:', handle);
}
if (productId) {
const firstProduct = await getFirstProduct(productId);
if (firstProduct) {
productSW = firstProduct;
}
}
return productSW ? transformProduct(productSW) : undefined;
}
export async function getProductRecommendations(productId: string): Promise<Product[]> {
const products = {} as unknown as ExtendedProductListingResult;
const res = await requestCrossSell(productId, getDefaultCrossSellingCriteria());
// @ToDo: Make this more dynamic to merge multiple Cross-Sellings, at the moment we only get the first one
if (res && res[0] && res[0].products) {
products.elements = res[0].products;
}
return products ? transformProducts(products) : [];
}
// This is called from `app/api/revalidate.ts` so providers can control revalidation logic.
export async function revalidate(req: NextRequest): Promise<NextResponse> {
return NextResponse.json({
status: 200,
message: 'This is currently not working and was never tested.',
now: Date.now()
});
// We always need to respond with a 200 status code,
// otherwise it will continue to retry the request.
const collectionWebhooks = ['collections/create', 'collections/delete', 'collections/update'];
const productWebhooks = ['products/create', 'products/delete', 'products/update'];
const topic = headers().get('x-shopware-topic') || 'unknown';
const secret = req.nextUrl.searchParams.get('secret');
const isCollectionUpdate = collectionWebhooks.includes(topic);
const isProductUpdate = productWebhooks.includes(topic);
if (!secret || secret !== process.env.SHOPWARE_REVALIDATION_SECRET) {
console.error('Invalid revalidation secret.');
return NextResponse.json({ status: 200 });
}
if (!isCollectionUpdate && !isProductUpdate) {
// We don't need to revalidate anything for any other topics.
return NextResponse.json({ status: 200 });
}
if (isCollectionUpdate) {
revalidateTag(TAGS.collections);
}
if (isProductUpdate) {
revalidateTag(TAGS.products);
}
return NextResponse.json({ status: 200, revalidated: true, now: Date.now() });
}