-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimportData.js
84 lines (70 loc) · 2.18 KB
/
importData.js
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
import { createClient } from '@sanity/client';
const client = createClient({
projectId: 'your-project-id',
dataset: 'production',
useCdn: true,
apiVersion: '2025-01-13',
token: 'your-auth-token',
});
async function uploadImageToSanity(imageUrl) {
try {
console.log(`Uploading image: ${imageUrl}`);
const response = await fetch(imageUrl);
if (!response.ok) {
throw new Error(`Failed to fetch image: ${imageUrl}`);
}
const buffer = await response.arrayBuffer();
const bufferImage = Buffer.from(buffer);
const asset = await client.assets.upload('image', bufferImage, {
filename: imageUrl.split('/').pop(),
});
console.log(`Image uploaded successfully: ${asset._id}`);
return asset._id;
} catch (error) {
console.error('Failed to upload image:', imageUrl, error);
return null;
}
}
async function uploadProduct(product) {
try {
const imageId = await uploadImageToSanity(product.imageUrl);
if (imageId) {
const document = {
_type: 'product',
title: product.title,
price: product.price,
productImage: {
_type: 'image',
asset: {
_ref: imageId,
},
},
tags: product.tags,
dicountPercentage: product.dicountPercentage, // Typo in field name: dicountPercentage -> discountPercentage
description: product.description,
isNew: product.isNew,
};
const createdProduct = await client.create(document);
console.log(`Product ${product.title} uploaded successfully:`, createdProduct);
} else {
console.log(`Product ${product.title} skipped due to image upload failure.`);
}
} catch (error) {
console.error('Error uploading product:', error);
}
}
async function importProducts() {
try {
const response = await fetch('https://template6-six.vercel.app/api/products');
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const products = await response.json();
for (const product of products) {
await uploadProduct(product);
}
} catch (error) {
console.error('Error fetching products:', error);
}
}
importProducts();