├── .gitignore ├── package.json ├── sanityClient.ts ├── tsconfig.json ├── sanityClient.js ├── dist ├── sanityClient.js └── importData.js ├── importData.ts └── importData.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | *.env -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "@sanity/client": "^6.24.1", 4 | "axios": "^1.7.9" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /sanityClient.ts: -------------------------------------------------------------------------------- 1 | // sanityClient.ts 2 | import { createClient } from '@sanity/client'; 3 | 4 | export const client = createClient({ 5 | projectId: process.env.projectId, // Replace with your project ID 6 | dataset: 'production', // Or your dataset name 7 | apiVersion: '2024-01-04', // Today's date or latest API version 8 | useCdn: false, // Disable CDN for real-time updates 9 | token: process.env.token, 10 | }); -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Language and Environment */ 4 | "target": "ES2020", 5 | 6 | /* Modules */ 7 | "module": "NodeNext", 8 | "moduleResolution": "NodeNext", 9 | "esModuleInterop": true, 10 | "forceConsistentCasingInFileNames": true, 11 | 12 | /* Type Checking */ 13 | "strict": true, 14 | "skipLibCheck": true, 15 | 16 | /* Output */ 17 | "outDir": "./dist" 18 | }, 19 | } -------------------------------------------------------------------------------- /sanityClient.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | exports.client = void 0; 4 | // sanityClient.ts 5 | var client_1 = require("@sanity/client"); 6 | exports.client = (0, client_1.createClient)({ 7 | projectId: 'rohwei6u', // Replace with your project ID 8 | dataset: 'production', // Or your dataset name 9 | apiVersion: '2024-01-04', // Today's date or latest API version 10 | useCdn: false, // Disable CDN for real-time updates 11 | token: "skwAYL2EVT699VvWODU6xcibH3o0mwbKP9DoMrexRkfzRpaWfQahfSiwEuAlwZqU4FibHyEoVOR8gmHnwnDXW640gZU3mp1afdgil0yTqqL9Oqw4pqTssSZERXnLbXopBPVqpiW0OVN7hTAH0fF7GbSjAKDDk9kbYAAZZpDfdWhYAHWmtFAY" 12 | }); 13 | -------------------------------------------------------------------------------- /dist/sanityClient.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | exports.client = void 0; 4 | // sanityClient.ts 5 | const client_1 = require("@sanity/client"); 6 | exports.client = (0, client_1.createClient)({ 7 | projectId: 'rohwei6u', // Replace with your project ID 8 | dataset: 'production', // Or your dataset name 9 | apiVersion: '2024-01-04', // Today's date or latest API version 10 | useCdn: false, // Disable CDN for real-time updates 11 | token: "skwAYL2EVT699VvWODU6xcibH3o0mwbKP9DoMrexRkfzRpaWfQahfSiwEuAlwZqU4FibHyEoVOR8gmHnwnDXW640gZU3mp1afdgil0yTqqL9Oqw4pqTssSZERXnLbXopBPVqpiW0OVN7hTAH0fF7GbSjAKDDk9kbYAAZZpDfdWhYAHWmtFAY" 12 | }); 13 | -------------------------------------------------------------------------------- /importData.ts: -------------------------------------------------------------------------------- 1 | import axios from 'axios'; 2 | import { client } from './sanityClient.js'; 3 | 4 | async function uploadImageToSanity(imageUrl: string): Promise { 5 | 6 | try { 7 | // Fetch the image from the URL and convert it to a buffer 8 | const response = await axios.get(imageUrl, { responseType: 'arraybuffer' }); 9 | const buffer = Buffer.from(response.data); 10 | 11 | // Upload the image to Sanity 12 | const asset = await client.assets.upload('image', buffer, { 13 | filename: imageUrl.split('/').pop(), // Extract the filename from URL 14 | }); 15 | 16 | // Debugging: Log the asset returned by Sanity 17 | console.log('Image uploaded successfully:', asset); 18 | 19 | return asset._id; // Return the uploaded image asset reference ID 20 | } catch (error) { 21 | console.error('❌ Failed to upload image:', imageUrl, error); 22 | throw error; 23 | } 24 | } 25 | 26 | async function importData() { 27 | try { 28 | // Fetch data from external API 29 | const response = await axios.get('https://fakestoreapi.com/products'); 30 | const products = response.data; 31 | 32 | // Iterate over the products 33 | for (const product of products) { 34 | let imageRef = ''; 35 | 36 | // Upload image and get asset reference if it exists 37 | if (product.image) { 38 | imageRef = await uploadImageToSanity(product.image); 39 | } 40 | 41 | const sanityProduct = { 42 | _id: `product-${product.id}`, // Prefix the ID to ensure validity 43 | _type: 'product', 44 | name: product.title, 45 | price: product.price, 46 | discountPercentage: product.discountPercentage || 0, 47 | tags: product.category ? [product.category] : [], 48 | image: { 49 | _type: 'image', 50 | asset: { 51 | _type: 'reference', 52 | _ref: imageRef, // Set the correct asset reference ID 53 | }, 54 | }, 55 | description: product.description, 56 | rating: product.rating?.rate || 0, 57 | ratingCount: product.rating?.count || 0, 58 | }; 59 | 60 | // Log the product before attempting to upload it to Sanity 61 | console.log('Uploading product:', sanityProduct); 62 | 63 | // Import data into Sanity 64 | await client.createOrReplace(sanityProduct); 65 | console.log(`✅ Imported product: ${sanityProduct.name}`); 66 | } 67 | 68 | console.log('✅ Data import completed!'); 69 | } catch (error) { 70 | console.error('❌ Error importing data:', error); 71 | } 72 | } 73 | 74 | importData(); -------------------------------------------------------------------------------- /dist/importData.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __importDefault = (this && this.__importDefault) || function (mod) { 3 | return (mod && mod.__esModule) ? mod : { "default": mod }; 4 | }; 5 | Object.defineProperty(exports, "__esModule", { value: true }); 6 | const axios_1 = __importDefault(require("axios")); 7 | const sanityClient_js_1 = require("./sanityClient.js"); 8 | async function uploadImageToSanity(imageUrl) { 9 | try { 10 | // Fetch the image from the URL and convert it to a buffer 11 | const response = await axios_1.default.get(imageUrl, { responseType: 'arraybuffer' }); 12 | const buffer = Buffer.from(response.data); 13 | // Upload the image to Sanity 14 | const asset = await sanityClient_js_1.client.assets.upload('image', buffer, { 15 | filename: imageUrl.split('/').pop(), // Extract the filename from URL 16 | }); 17 | // Debugging: Log the asset returned by Sanity 18 | console.log('Image uploaded successfully:', asset); 19 | return asset._id; // Return the uploaded image asset reference ID 20 | } 21 | catch (error) { 22 | console.error('❌ Failed to upload image:', imageUrl, error); 23 | throw error; 24 | } 25 | } 26 | async function importData() { 27 | try { 28 | // Fetch data from external API 29 | const response = await axios_1.default.get('https://fakestoreapi.com/products'); 30 | const products = response.data; 31 | // Iterate over the products 32 | for (const product of products) { 33 | let imageRef = ''; 34 | // Upload image and get asset reference if it exists 35 | if (product.image) { 36 | imageRef = await uploadImageToSanity(product.image); 37 | } 38 | const sanityProduct = { 39 | _id: `product-${product.id}`, // Prefix the ID to ensure validity 40 | _type: 'product', 41 | name: product.title, 42 | price: product.price, 43 | discountPercentage: product.discountPercentage || 0, 44 | tags: product.category ? [product.category] : [], 45 | image: { 46 | _type: 'image', 47 | asset: { 48 | _type: 'reference', 49 | _ref: imageRef, // Set the correct asset reference ID 50 | }, 51 | }, 52 | description: product.description, 53 | rating: product.rating?.rate || 0, 54 | ratingCount: product.rating?.count || 0, 55 | }; 56 | // Log the product before attempting to upload it to Sanity 57 | console.log('Uploading product:', sanityProduct); 58 | // Import data into Sanity 59 | await sanityClient_js_1.client.createOrReplace(sanityProduct); 60 | console.log(`✅ Imported product: ${sanityProduct.name}`); 61 | } 62 | console.log('✅ Data import completed!'); 63 | } 64 | catch (error) { 65 | console.error('❌ Error importing data:', error); 66 | } 67 | } 68 | importData(); 69 | -------------------------------------------------------------------------------- /importData.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 3 | function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 4 | return new (P || (P = Promise))(function (resolve, reject) { 5 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 6 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 7 | function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 8 | step((generator = generator.apply(thisArg, _arguments || [])).next()); 9 | }); 10 | }; 11 | var __generator = (this && this.__generator) || function (thisArg, body) { 12 | var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); 13 | return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; 14 | function verb(n) { return function (v) { return step([n, v]); }; } 15 | function step(op) { 16 | if (f) throw new TypeError("Generator is already executing."); 17 | while (g && (g = 0, op[0] && (_ = 0)), _) try { 18 | if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; 19 | if (y = 0, t) op = [op[0] & 2, t.value]; 20 | switch (op[0]) { 21 | case 0: case 1: t = op; break; 22 | case 4: _.label++; return { value: op[1], done: false }; 23 | case 5: _.label++; y = op[1]; op = [0]; continue; 24 | case 7: op = _.ops.pop(); _.trys.pop(); continue; 25 | default: 26 | if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } 27 | if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } 28 | if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } 29 | if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } 30 | if (t[2]) _.ops.pop(); 31 | _.trys.pop(); continue; 32 | } 33 | op = body.call(thisArg, _); 34 | } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } 35 | if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; 36 | } 37 | }; 38 | Object.defineProperty(exports, "__esModule", { value: true }); 39 | var axios_1 = require("axios"); 40 | var sanityClient_js_1 = require("./sanityClient.js"); 41 | function uploadImageToSanity(imageUrl) { 42 | return __awaiter(this, void 0, void 0, function () { 43 | var response, buffer, asset, error_1; 44 | return __generator(this, function (_a) { 45 | switch (_a.label) { 46 | case 0: 47 | _a.trys.push([0, 3, , 4]); 48 | return [4 /*yield*/, axios_1.default.get(imageUrl, { responseType: 'arraybuffer' })]; 49 | case 1: 50 | response = _a.sent(); 51 | buffer = Buffer.from(response.data); 52 | return [4 /*yield*/, sanityClient_js_1.client.assets.upload('image', buffer, { 53 | filename: imageUrl.split('/').pop(), // Extract the filename from URL 54 | })]; 55 | case 2: 56 | asset = _a.sent(); 57 | // Debugging: Log the asset returned by Sanity 58 | console.log('Image uploaded successfully:', asset); 59 | return [2 /*return*/, asset._id]; // Return the uploaded image asset reference ID 60 | case 3: 61 | error_1 = _a.sent(); 62 | console.error('❌ Failed to upload image:', imageUrl, error_1); 63 | throw error_1; 64 | case 4: return [2 /*return*/]; 65 | } 66 | }); 67 | }); 68 | } 69 | function importData() { 70 | return __awaiter(this, void 0, void 0, function () { 71 | var response, products, _i, products_1, product, imageRef, sanityProduct, error_2; 72 | var _a, _b; 73 | return __generator(this, function (_c) { 74 | switch (_c.label) { 75 | case 0: 76 | _c.trys.push([0, 8, , 9]); 77 | return [4 /*yield*/, axios_1.default.get('https://fakestoreapi.com/products')]; 78 | case 1: 79 | response = _c.sent(); 80 | products = response.data; 81 | _i = 0, products_1 = products; 82 | _c.label = 2; 83 | case 2: 84 | if (!(_i < products_1.length)) return [3 /*break*/, 7]; 85 | product = products_1[_i]; 86 | imageRef = ''; 87 | if (!product.image) return [3 /*break*/, 4]; 88 | return [4 /*yield*/, uploadImageToSanity(product.image)]; 89 | case 3: 90 | imageRef = _c.sent(); 91 | _c.label = 4; 92 | case 4: 93 | sanityProduct = { 94 | _id: "product-".concat(product.id), // Prefix the ID to ensure validity 95 | _type: 'product', 96 | name: product.title, 97 | price: product.price, 98 | discountPercentage: product.discountPercentage || 0, 99 | tags: product.category ? [product.category] : [], 100 | image: { 101 | _type: 'image', 102 | asset: { 103 | _type: 'reference', 104 | _ref: imageRef, // Set the correct asset reference ID 105 | }, 106 | }, 107 | description: product.description, 108 | rating: ((_a = product.rating) === null || _a === void 0 ? void 0 : _a.rate) || 0, 109 | ratingCount: ((_b = product.rating) === null || _b === void 0 ? void 0 : _b.count) || 0, 110 | }; 111 | // Log the product before attempting to upload it to Sanity 112 | console.log('Uploading product:', sanityProduct); 113 | // Import data into Sanity 114 | return [4 /*yield*/, sanityClient_js_1.client.createOrReplace(sanityProduct)]; 115 | case 5: 116 | // Import data into Sanity 117 | _c.sent(); 118 | console.log("\u2705 Imported product: ".concat(sanityProduct.name)); 119 | _c.label = 6; 120 | case 6: 121 | _i++; 122 | return [3 /*break*/, 2]; 123 | case 7: 124 | console.log('✅ Data import completed!'); 125 | return [3 /*break*/, 9]; 126 | case 8: 127 | error_2 = _c.sent(); 128 | console.error('❌ Error importing data:', error_2); 129 | return [3 /*break*/, 9]; 130 | case 9: return [2 /*return*/]; 131 | } 132 | }); 133 | }); 134 | } 135 | importData(); 136 | --------------------------------------------------------------------------------