Sample codes > Sample courier - Canada Post
Sample courier - Canada Post
As with any LLM AI model outputs, always verify the generated code for accuracy before deploying it live.
For the sample prompts here, your might get different responses since AI models have random elements.
AI Prompt:
I'd like a shipping rate calculator that uses the Canada Post rates.
The dimensions of the parcels are contained in the items metafield namespace object called "carton". Get the first 15 values in the namespace. The parcels dimension as input to get the rates. If the data currency is different from "CAD"; convert the resulting rates fee from "CAD" to the data currency. Also, set the rates currency to the data currency. Make sure to implement async functions correctly.
AI Output:
// Import necessary modules
import { enrichItemDetails, CanadaPost, Currency, print } from './modules.js';
export async function calculateShippingRates(DATA, env) {
try {
// Enrich item details with the "carton" namespace for parcel dimensions
DATA = await enrichItemDetails(DATA, [{ namespace: "shipping", size: 15 }]);
// Extract parcel dimensions and convert them to the required format for CanadaPost
const parcels = DATA.items.map(item => {
const carton = item.metafields && item.metafields.shipping;
return {
length: carton && carton.length,
width: carton && carton.width,
height: carton && carton.height,
weight: item.grams / 1000, // Convert grams to kg
quantity: item.quantity
};
});
// Initialize the CanadaPost class
const canadaPost = new CanadaPost(DATA.origin, DATA.destination);
let rates = await canadaPost.getRates(parcels);
// Check if currency conversion is needed
if (DATA.currency !== "CAD") {
const currencyConverter = new Currency();
rates = await Promise.all(rates.map(async rate => {
rate.total_price = await currencyConverter.convert(rate.total_price, "CAD", DATA.currency);
rate.currency = DATA.currency;
return rate;
}));
}
return { rates };
} catch (error) {
// Use the print function in place of console.log
print("Error in calculateShippingRates", error);
// Return a default rate in case of any error
return {
rates: [{
service_name: "",
service_code: "",
total_price: null,
description: "",
currency: "",
min_delivery_date: "",
max_delivery_date: ""
}]
};
}
}