oc-tryton-rpc/examples/advanced.js

201 lines
6.5 KiB
JavaScript

/**
* Advanced usage examples for Tryton RPC Client
*/
const { TrytonClient, Fault, ProtocolError } = require("../src");
async function advancedExamples() {
console.log("🔬 Advanced Tryton RPC Client Examples");
console.log("=====================================\n");
const client = new TrytonClient({
hostname: "localhost",
database: "tryton",
username: "admin",
password: "admin",
options: {
verbose: false,
cache: true,
keepMax: 6,
timeout: 45000,
},
});
try {
await client.connect();
console.log("✅ Connected to Tryton server\n");
// Example 1: Batch operations
console.log("📦 Example 1: Batch Operations");
console.log("------------------------------");
const batchData = [
{ name: "Company A", code: "COMP_A" },
{ name: "Company B", code: "COMP_B" },
{ name: "Company C", code: "COMP_C" },
];
const createdIds = await client.create("party.party", batchData);
console.log("Created parties:", createdIds);
// Read them back
const createdParties = await client.read("party.party", createdIds, [
"id",
"name",
"code",
]);
console.log("Created party details:", createdParties);
console.log();
// Example 2: Complex search with domain
console.log("🔍 Example 2: Complex Search");
console.log("---------------------------");
const complexDomain = [
"OR",
[["name", "like", "Company%"]],
[["code", "like", "COMP_%"]],
];
const foundIds = await client.search("party.party", complexDomain);
console.log("Found IDs with complex domain:", foundIds);
const foundParties = await client.searchRead(
"party.party",
complexDomain,
["id", "name", "code"],
0, // offset
10 // limit
);
console.log("Found parties:", foundParties);
console.log();
// Example 3: Update operations
console.log("✏️ Example 3: Update Operations");
console.log("------------------------------");
if (createdIds.length > 0) {
await client.write("party.party", [createdIds[0]], {
name: "Updated Company Name",
});
console.log(`Updated party ${createdIds[0]}`);
// Verify update
const updated = await client.read(
"party.party",
[createdIds[0]],
["id", "name", "code"]
);
console.log("Updated party:", updated[0]);
}
console.log();
// Example 4: Parallel operations
console.log("⚡ Example 4: Parallel Operations");
console.log("--------------------------------");
const parallelCalls = [
{ method: "model.party.party.search_count", args: [[]] },
{ method: "model.company.company.search_count", args: [[]] },
{ method: "common.version", args: [] },
];
const parallelResults = await client.callParallel(parallelCalls);
console.log("Parallel results:");
console.log("- Total parties:", parallelResults[0]);
console.log("- Total companies:", parallelResults[1]);
console.log("- Server version:", parallelResults[2]);
console.log();
// Example 5: Working with dates
console.log("📅 Example 5: Working with Dates");
console.log("-------------------------------");
const today = new Date();
const tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate() + 1);
console.log("Today:", today.toISOString());
console.log("Tomorrow:", tomorrow.toISOString());
// Note: Date handling depends on your specific Tryton models
// This is just to show how dates are serialized
console.log();
// Example 6: Error handling patterns
console.log("⚠️ Example 6: Error Handling");
console.log("---------------------------");
try {
await client.call("nonexistent.model.method", []);
} catch (error) {
if (error instanceof Fault) {
console.log("✅ Caught RPC Fault:", error.faultCode);
} else if (error instanceof ProtocolError) {
console.log("✅ Caught Protocol Error:", error.errcode);
} else {
console.log("✅ Caught Generic Error:", error.message);
}
}
try {
await client.read("party.party", [999999], ["name"]);
} catch (error) {
console.log(
"✅ Caught read error (likely record not found):",
error.message
);
}
console.log();
// Example 7: Cache usage
console.log("💾 Example 7: Cache Usage");
console.log("------------------------");
// First call - will hit server
console.time("First call");
const result1 = await client.read("party.party", [1], ["name"]);
console.timeEnd("First call");
// Second call - should be faster due to cache
console.time("Second call (cached)");
const result2 = await client.read("party.party", [1], ["name"]);
console.timeEnd("Second call (cached)");
console.log(
"Results are equal:",
JSON.stringify(result1) === JSON.stringify(result2)
);
// Clear cache
client.clearCache();
console.log("Cache cleared");
console.log();
// Cleanup: Delete created test records
console.log("🧹 Cleanup: Deleting test records");
console.log("---------------------------------");
if (createdIds.length > 0) {
try {
await client.delete("party.party", createdIds);
console.log("✅ Deleted test records:", createdIds);
} catch (error) {
console.log("⚠️ Could not delete test records:", error.message);
}
}
} catch (error) {
console.error("❌ Advanced examples failed:", error.message);
console.error(error.stack);
} finally {
client.close();
console.log("\n👋 Advanced examples completed");
}
}
if (require.main === module) {
advancedExamples().catch(console.error);
}
module.exports = { advancedExamples };