76 lines
2.7 KiB
TypeScript
76 lines
2.7 KiB
TypeScript
import * as fs from "fs";
|
|
import * as path from "path";
|
|
|
|
const API_BASE = process.env.API_BASE || "https://api.homaroma.shop/api";
|
|
const ADMIN_USER = process.env.ADMIN_USER || "admin";
|
|
const ADMIN_PASS = process.env.ADMIN_PASS || "homaroma123";
|
|
|
|
async function main() {
|
|
console.log(`=== Importing Attribute Definitions via API (${API_BASE}) ===`);
|
|
|
|
// 1. Read JSON definitions
|
|
const jsonPath = path.resolve(__dirname, "../data/homaroma_attribute_definitions.json");
|
|
if (!fs.existsSync(jsonPath)) {
|
|
throw new Error(`File not found: ${jsonPath}`);
|
|
}
|
|
const definitions = JSON.parse(fs.readFileSync(jsonPath, "utf-8"));
|
|
console.log(`✓ Loaded ${definitions.length} definitions from data/homaroma_attribute_definitions.json`);
|
|
|
|
// 2. Login to get JWT Token
|
|
console.log(`2. Logging in as '${ADMIN_USER}' to obtain JWT token...`);
|
|
const loginRes = await fetch(`${API_BASE}/auth/login`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ username: ADMIN_USER, password: ADMIN_PASS }),
|
|
});
|
|
|
|
if (!loginRes.ok) {
|
|
const errorText = await loginRes.text();
|
|
throw new Error(`Login failed (${loginRes.status}): ${errorText}`);
|
|
}
|
|
|
|
const loginData = (await loginRes.json()) as { success: boolean; token: string };
|
|
if (!loginData.token) {
|
|
throw new Error("No token returned from login API");
|
|
}
|
|
const token = loginData.token;
|
|
console.log("✓ Successfully authenticated. JWT token acquired.");
|
|
|
|
// 3. Post bulk-import
|
|
console.log("3. Sending bulk-import payload to /product-attributes/definitions/bulk-import...");
|
|
const importRes = await fetch(`${API_BASE}/product-attributes/definitions/bulk-import`, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
Authorization: `Bearer ${token}`,
|
|
},
|
|
body: JSON.stringify(definitions),
|
|
});
|
|
|
|
if (!importRes.ok) {
|
|
const errorText = await importRes.text();
|
|
throw new Error(`Bulk import failed (${importRes.status}): ${errorText}`);
|
|
}
|
|
|
|
const importResult = await importRes.json();
|
|
console.log("✓ Bulk import response:", JSON.stringify(importResult, null, 2));
|
|
|
|
// 4. Fetch all definitions to verify
|
|
console.log("4. Verifying active attribute definitions from API...");
|
|
const listRes = await fetch(`${API_BASE}/product-attributes/definitions?lang=th`);
|
|
const listData = await listRes.json();
|
|
console.log(`✓ Total active attribute definitions on API: ${Array.isArray(listData) ? listData.length : 'N/A'}`);
|
|
|
|
return importResult;
|
|
}
|
|
|
|
main()
|
|
.then(() => {
|
|
console.log("\n✅ Completed successfully.");
|
|
process.exit(0);
|
|
})
|
|
.catch((err) => {
|
|
console.error("\n❌ Error:", err.message || err);
|
|
process.exit(1);
|
|
});
|