-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemp_codescript.txt
436 lines (363 loc) · 11.5 KB
/
temp_codescript.txt
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
// src/databases/products.ts:
import { sql } from '../utils/connect';
import { Product } from '../types/Product';
export async function getAllProducts(): Promise<Product[]> {
try {
const products = await sql<Product[]>`
SELECT id, name, type, description, price, shader_path AS "shaderPath" FROM products LIMIT 10
`;
return products;
} catch (error) {
console.error('Error fetching products from database:', error);
return [];
}
}
export async function getProductById(id: number): Promise<Product | null> {
try {
const [product] = await sql<Product[]>`
SELECT id, name, type, description, price, shader_path AS "shaderPath" FROM products WHERE id = ${id}
`;
return product || null;
} catch (error) {
console.error('Error fetching product by ID from database:', error);
return null;
}
}
----------------------------------------
// src/app/product/[id]/page.tsx:
import Image from 'next/image';
import { getProductById } from '../../../databases/products';
import { Product } from '../../../types/Product';
import ShaderImage1 from '../../../components/ShaderImage1';
import ShaderImage2 from '../../../components/ShaderImage2';
import ShaderImage3 from '../../../components/ShaderImage3';
import ShaderImage4 from '../../../components/ShaderImage4';
import AddToCartButton from '../../../components/AddToCartButton';
interface ProductPageProps {
params: { id: string };
}
export default async function ProductPage({ params }: ProductPageProps) {
const product: Product | null = await getProductById(Number(params.id));
if (!product) {
return (
<div className="container mx-auto p-7 pt-0">
<p>Product not found</p>
</div>
);
}
return (
<div className="container mx-auto p-6 pt-0">
<div className="rounded-lg bg-yellow-50 bg-opacity-60 overflow-hidden shadow-md p-6 flex">
{product.shaderPath && (
<div className="mr-8">
{product.shaderPath === 'ShaderImage1' && (
<ShaderImage1 width={300} height={300} />
)}
{product.shaderPath === 'ShaderImage2' && (
<ShaderImage2 width={300} height={300} />
)}
{product.shaderPath === 'ShaderImage3' && (
<ShaderImage3 width={300} height={300} />
)}
{product.shaderPath === 'ShaderImage4' && (
<ShaderImage4 width={300} height={300} />
)}
</div>
)}
{!product.shaderPath && (
<Image
src={product.image}
alt={product.name}
className="mr-8"
style={{ width: '300px', height: '300px', objectFit: 'cover' }}
data-test-id="product-image"
/>
)}
<div>
<h1 className="text-2xl font-bold mb-4">{product.name}</h1>
<p
className="text-xl font-semibold mb-4"
data-test-id="product-price"
>
${product.price}
</p>
<p className="mb-8">{product.description}</p>
<AddToCartButton product={product} />
</div>
</div>
</div>
);
}
----------------------------------------
// src/app/productspage/page.tsx:
import Image from 'next/image';
import Link from 'next/link';
import { getAllProducts } from '../../databases/products';
import { Product } from '../../types/Product';
import ShaderImage1 from '../../components/ShaderImage1';
import ShaderImage2 from '../../components/ShaderImage2';
import ShaderImage3 from '../../components/ShaderImage3';
import ShaderImage4 from '../../components/ShaderImage4';
type ProductLinkProps = {
product: Product;
};
const ProductLink: React.FC<ProductLinkProps> = ({ product }) => {
return (
<Link
href={`/product/${product.id.toString()}`}
key={product.id}
data-test-id={`product-${product.id}`}
className="product-card"
>
<div style={{ cursor: 'pointer' }}>
{product.shaderPath ? (
<div className="rounded-lg overflow-hidden">
{product.shaderPath === 'ShaderImage1' && (
<ShaderImage1 width={300} height={300} />
)}
{product.shaderPath === 'ShaderImage2' && (
<ShaderImage2 width={300} height={300} />
)}
{product.shaderPath === 'ShaderImage3' && (
<ShaderImage3 width={300} height={300} />
)}
{product.shaderPath === 'ShaderImage4' && (
<ShaderImage4 width={300} height={300} />
)}
</div>
) : (
<Image
src={product.image}
alt={product.name}
width={300}
height={300}
className="rounded-lg mb-4"
/>
)}
<h2>{product.name}</h2>
</div>
</Link>
);
};
const ProductsPage: React.FC = async () => {
try {
const products: Product[] = await getAllProducts();
console.log('Obtained products:', products);
if (!products || products.length === 0) {
console.log('Products not found');
}
return (
<div className="container mx-auto p-6 pt-0">
<div className="product-list">
{products.length === 0 ? (
<p>No products found.</p>
) : (
products.map((product) => (
<ProductLink product={product} key={product.id} />
))
)}
</div>
</div>
);
} catch (error) {
console.error('Error fetching products:', error);
return (
<div className="container mx-auto p-7 pt-0">
<p>Error fetching products</p>
</div>
);
}
};
export default ProductsPage;
----------------------------------------
// src/types/Params.ts:
export interface Params {
id: string;
}
----------------------------------------
// src/types/Product.ts:
export interface Product {
id: number;
name: string;
type: string;
description: string;
image: string;
price: number;
shaderPath: string | null;
}
----------------------------------------
// src/utils/__tests__/cartSum.test.ts:
const calculateCartTotal = (cart: { price: number; quantity: number }[]) => {
return cart.reduce(
(total, product) => total + product.price * product.quantity,
0,
);
};
test('calculates the total price of the cart', () => {
const cart = [
{ id: 1, price: 10, quantity: 2 },
{ id: 2, price: 20, quantity: 1 },
];
const total = calculateCartTotal(cart);
expect(total).toBe(40);
});
----------------------------------------
// src/utils/__tests__/combineProdutData.test.ts:
import { getProducts } from '../../databases/products';
import { getCartFromCookies } from '../cookies';
import { Product } from '../../types/Product';
jest.mock('../../databases/products', () => ({
getProducts: jest.fn(),
}));
jest.mock('../cookies', () => ({
getCartFromCookies: jest.fn(),
}));
const combineProductData = async () => {
const products: Product[] = await getProducts();
const cart = getCartFromCookies();
return cart.map((cartItem: { id: number; quantity: number }) => {
const product = products.find((product) => product.id === cartItem.id);
return {
...product,
quantity: cartItem.quantity,
};
});
};
test('combines product data with quantity data', async () => {
const mockProducts = [
{
id: 1,
name: 'Product 1',
type: 'Type 1',
description: 'Description 1',
price: 10,
shaderPath: null,
},
{
id: 2,
name: 'Product 2',
type: 'Type 2',
description: 'Description 2',
price: 20,
shaderPath: null,
},
];
const mockCart = [
{ id: 1, quantity: 2 },
{ id: 2, quantity: 3 },
];
(getProducts as jest.Mock).mockResolvedValue(mockProducts);
(getCartFromCookies as jest.Mock).mockReturnValue(mockCart);
const combinedData = await combineProductData();
expect(combinedData).toBeDefined();
expect(combinedData[0]).toHaveProperty('id');
expect(combinedData[0]).toHaveProperty('quantity');
expect(combinedData[0].quantity).toBe(2);
});
----------------------------------------
// src/utils/__tests__/updateCartItemQuantity.test.ts:
import { getCartFromCookies, saveCartToCookies } from '../cookies';
const updateCartItemQuantity = (id: number, quantity: number) => {
const cart = getCartFromCookies();
const updatedCart = cart.map((item: { id: number; quantity: number }) =>
item.id === id ? { ...item, quantity } : item,
);
saveCartToCookies(updatedCart);
};
test('updates the quantity of an existing cart item', () => {
// Mock initial cart data
const initialCart = [{ id: 1, quantity: 1 }];
document.cookie = `cart=${JSON.stringify(initialCart)}`;
updateCartItemQuantity(1, 3);
const updatedCart = getCartFromCookies();
expect(updatedCart[0].quantity).toBe(3);
});
----------------------------------------
// src/utils/config.js:
import postgres from 'postgres';
import { config } from 'dotenv-safe';
export const postgresConfig = {
ssl: Boolean(process.env.POSTGRES_URL),
transform: {
...postgres.camel,
undefined: null,
},
};
export function setEnvironmentVariables() {
if (process.env.NODE_ENV === 'production' || process.env.CI) {
if (process.env.POSTGRES_URL) {
process.env.PGHOST = process.env.POSTGRES_HOST;
process.env.PGDATABASE = process.env.POSTGRES_DATABASE;
process.env.PGUSERNAME = process.env.POSTGRES_USER;
process.env.PGPASSWORD = process.env.POSTGRES_PASSWORD;
}
return;
}
config();
}
----------------------------------------
// src/utils/connect.ts:
import 'server-only';
import postgres, { Sql } from 'postgres';
import postgresConfig from '../../ley.config.js';
import { setEnvironmentVariables } from './config.js';
setEnvironmentVariables();
declare global {
var postgresSqlClient: Sql | undefined;
}
function connectOneTimeToDatabase() {
if (!globalThis.postgresSqlClient) {
globalThis.postgresSqlClient = postgres(postgresConfig);
}
return ((
...sqlParameters: Parameters<typeof globalThis.postgresSqlClient>
) => {
return globalThis.postgresSqlClient!(...sqlParameters);
}) as typeof globalThis.postgresSqlClient;
}
export const sql = connectOneTimeToDatabase();
----------------------------------------
// src/utils/cookies.js:
import secureJsonParse from 'secure-json-parse';
export const getCartFromCookies = () => {
if (typeof document !== 'undefined') {
const name = 'cart=';
const decodedCookie = decodeURIComponent(document.cookie);
const ca = decodedCookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1);
}
if (c.indexOf(name) === 0) {
return secureJsonParse(c.substring(name.length, c.length));
}
}
}
return [];
};
export const saveCartToCookies = (cart) => {
if (typeof document !== 'undefined') {
const expires = new Date();
expires.setTime(expires.getTime() + 24 * 60 * 60 * 1000); // 1 day
document.cookie = `cart=${JSON.stringify(cart)};expires=${expires.toUTCString()};path=/`;
}
};
export const removeCartFromCookies = () => {
if (typeof document !== 'undefined') {
document.cookie = 'cart=; Max-Age=0; path=/';
}
};
----------------------------------------
// src/utils/serverCookies.js:
// src/utils/serverCookies.js
import { cookies } from 'next/headers';
export const getCartFromCookies = () => {
const cookieStore = cookies();
const cartCookie = cookieStore.get('cart');
if (cartCookie) {
return JSON.parse(cartCookie.value);
}
return [];
};
----------------------------------------