Utilities Examples
Production-ready code examples for common use cases.
E-commerce Checkout Flow
Complete shipping cost calculation for e-commerce checkout.
Multi-Carrier Comparison
typescript
import { DeClient } from '@dedot/sdk'
const client = new DeClient({
apiKey: process.env.DE_API_KEY,
workspace: 'my-ecommerce-store'
})
async function getShippingOptions(order) {
const { destination, items } = order
// Calculate total weight
const totalWeight = items.reduce((sum, item) => sum + item.weight, 0)
// Get shipping options for different service levels
const [sameDayFee, nextDayFee, standardFee] = await Promise.all([
client.realm.utilities.delivery.calculate({
origin: { country: 'NG', city: 'Lagos' },
destination,
serviceLevel: 'SAME_DAY',
weight: { value: totalWeight, unit: 'kg' }
}),
client.realm.utilities.delivery.calculate({
origin: { country: 'NG', city: 'Lagos' },
destination,
serviceLevel: 'NEXT_DAY',
weight: { value: totalWeight, unit: 'kg' }
}),
client.realm.utilities.delivery.calculate({
origin: { country: 'NG', city: 'Lagos' },
destination,
serviceLevel: 'STANDARD',
weight: { value: totalWeight, unit: 'kg' }
})
])
return [
{
service: 'Same Day',
cost: sameDayFee.totalFee,
currency: sameDayFee.currency,
deliveryTime: '6-8 hours',
confidence: sameDayFee.metadata.confidence
},
{
service: 'Next Day',
cost: nextDayFee.totalFee,
currency: nextDayFee.currency,
deliveryTime: '24 hours',
confidence: nextDayFee.metadata.confidence
},
{
service: 'Standard',
cost: standardFee.totalFee,
currency: standardFee.currency,
deliveryTime: '3-5 days',
confidence: standardFee.metadata.confidence
}
]
}
// Usage in checkout
const order = {
destination: {
country: 'NG',
city: 'Abuja',
coordinates: [9.0765, 7.3986]
},
items: [
{ sku: 'PROD-001', quantity: 2, weight: 1.5 },
{ sku: 'PROD-002', quantity: 1, weight: 0.8 }
]
}
const shippingOptions = await getShippingOptions(order)
console.log('Available Shipping Options:')
shippingOptions.forEach(option => {
console.log(`${option.service}: ${option.cost} ${option.currency} - ${option.deliveryTime}`)
})Output:
Available Shipping Options:
Same Day: 15000 NGN - 6-8 hours
Next Day: 8500 NGN - 24 hours
Standard: 4200 NGN - 3-5 daysFreight Quote Generator
Generate freight quotes for transport requests.
Multi-Modal Comparison
typescript
async function generateFreightQuote(shipment) {
const { origin, destination, cargo } = shipment
// Calculate fares for different transport modes
const quotes = await Promise.all([
// Road freight
client.realm.utilities.transport.calculate({
origin,
destination,
transportMode: 'ROAD',
vehicleType: 'CONTAINER_TRUCK',
cargo,
urgency: 'STANDARD'
}),
// Air freight
client.realm.utilities.transport.calculate({
origin,
destination,
transportMode: 'AIR',
vehicleType: 'CARGO_PLANE',
cargo,
urgency: 'URGENT'
}),
// Sea freight
client.realm.utilities.transport.calculate({
origin,
destination,
transportMode: 'SEA',
vehicleType: 'CONTAINER_SHIP',
cargo,
urgency: 'ECONOMY'
})
])
return quotes.map((quote, index) => ({
mode: ['ROAD', 'AIR', 'SEA'][index],
totalCost: quote.totalFare,
currency: quote.currency,
distance: `${quote.distance.kilometer} km`,
estimatedDuration: quote.estimatedDuration,
breakdown: {
baseFare: quote.baseFare,
distanceFare: quote.distanceFare,
fuelSurcharge: quote.fuelSurcharge
},
dataSource: quote.metadata.dataSource,
confidence: quote.metadata.confidence
}))
}
// Usage
const shipment = {
origin: {
country: 'NG',
city: 'Lagos',
coordinates: [6.5244, 3.3792]
},
destination: {
country: 'NG',
city: 'Kano',
coordinates: [12.0022, 8.5920]
},
cargo: {
weight: { value: 10000, unit: 'kg' },
volume: { value: 30, unit: 'm3' },
type: 'GENERAL',
hazardous: false
}
}
const quotes = await generateFreightQuote(shipment)
quotes.forEach(quote => {
console.log(`\n${quote.mode} Freight:`)
console.log(` Cost: ${quote.totalCost} ${quote.currency}`)
console.log(` Distance: ${quote.distance}`)
console.log(` Duration: ${quote.estimatedDuration?.day} days`)
console.log(` Data Source: ${quote.dataSource}`)
})Ride-Hailing Integration
Real-time ride pricing for ride-hailing app.
Fare Estimation with Driver Search
typescript
async function getRideEstimate(pickup, dropoff, vehicleClass = 'ECONOMY') {
// Calculate ride fare with nearby driver search
const rideFare = await client.realm.utilities.ride.calculate({
pickup,
dropoff,
vehicleClass,
passengerCount: 1,
includeNearbyDrivers: true
})
// Format response for mobile app
return {
pricing: {
basePrice: rideFare.estimatedFare.baseFare,
estimatedTotal: rideFare.estimatedFare.totalAfterSurge,
currency: rideFare.estimatedFare.currency,
breakdown: {
base: rideFare.estimatedFare.baseFare,
distance: rideFare.estimatedFare.distanceFare,
time: rideFare.estimatedFare.timeFare,
surge: rideFare.estimatedFare.surgeFare,
booking: rideFare.estimatedFare.bookingFee
}
},
surge: {
active: rideFare.surgeInfo.isActive,
multiplier: rideFare.surgeInfo.multiplier,
reason: rideFare.surgeInfo.reason
},
trip: {
distance: `${rideFare.tripEstimate.distance.kilometer} km`,
duration: `${rideFare.tripEstimate.duration.minute} min`,
confidence: rideFare.tripEstimate.confidence
},
pickup: {
eta: `${rideFare.pickupEstimate.eta.minute} min`,
driversNearby: rideFare.pickupEstimate.nearbyDrivers
}
}
}
// Usage - Economy ride
const economyRide = await getRideEstimate(
{ country: 'GH', city: 'Accra', coordinates: [5.6037, -0.1870] },
{ country: 'GH', coordinates: [5.6500, -0.2000] },
'ECONOMY'
)
console.log('Economy Ride Estimate:')
console.log(` Price: ${economyRide.pricing.estimatedTotal} ${economyRide.pricing.currency}`)
console.log(` Surge: ${economyRide.surge.multiplier}x - ${economyRide.surge.reason}`)
console.log(` Trip: ${economyRide.trip.distance} in ${economyRide.trip.duration}`)
console.log(` Pickup: ${economyRide.pickup.eta} (${economyRide.pickup.driversNearby} drivers nearby)`)
// Usage - Compare vehicle classes
const classes = ['ECONOMY', 'STANDARD', 'PREMIUM']
const estimates = await Promise.all(
classes.map(cls => getRideEstimate(pickup, dropoff, cls))
)
console.log('\nCompare Vehicle Classes:')
estimates.forEach((est, i) => {
console.log(`${classes[i]}: ${est.pricing.estimatedTotal} ${est.pricing.currency}`)
})Output:
Economy Ride Estimate:
Price: 18.75 USD
Surge: 1.5x - Peak hours
Trip: 6.2 km in 12 min
Pickup: 3 min (5 drivers nearby)
Compare Vehicle Classes:
ECONOMY: 18.75 USD
STANDARD: 22.50 USD
PREMIUM: 35.00 USDInternational E-commerce
Cross-border shipping with customs calculation.
Import Cost Calculator
typescript
async function calculateImportCost(product, destination) {
const { origin, weight, value, hsCode, description } = product
// Calculate cross-border fare
const crossBorder = await client.realm.utilities.crossborder.calculate({
origin,
destination,
shipment: {
weight: { value: weight, unit: 'kg' },
declaredValue: { amount: value, currency: 'USD' },
hsCode,
description,
quantity: 1
},
transportMode: 'AIR',
incoterms: 'DDP' // Delivered Duty Paid
})
// Format for customer display
return {
summary: {
productValue: value,
totalLandedCost: crossBorder.totalCost.amount,
currency: crossBorder.totalCost.currency,
savings: value * 0.1 // Example: 10% discount
},
breakdown: {
shipping: crossBorder.breakdown.transportFee.amount,
customsDuty: crossBorder.breakdown.customsDuty?.amount || 0,
vat: crossBorder.breakdown.vat?.amount || 0,
importTax: crossBorder.breakdown.importTax?.amount || 0,
brokerage: crossBorder.breakdown.brokerageFee.amount,
otherFees: crossBorder.breakdown.documentationFee.amount +
crossBorder.breakdown.borderCrossingFee.amount
},
duties: crossBorder.duties ? {
rate: `${crossBorder.duties.rate}%`,
amount: crossBorder.duties.amount.amount,
hsCode: crossBorder.duties.hsCode
} : null,
shipping: {
clearanceTime: `${crossBorder.estimatedClearanceTime.min.day}-${crossBorder.estimatedClearanceTime.max.day} days`,
requiredDocuments: crossBorder.requiredDocuments
},
disclaimer: crossBorder.metadata.disclaimer
}
}
// Usage - Import smartphone from US to Nigeria
const product = {
origin: { country: 'US', city: 'Los Angeles' },
destination: { country: 'NG', city: 'Lagos' },
weight: 0.5,
value: 1200,
hsCode: '8517.12',
description: 'Smartphone - iPhone 14 Pro'
}
const importCost = await calculateImportCost(product, product.destination)
console.log('Import Cost Breakdown:')
console.log(`Product Value: $${importCost.summary.productValue}`)
console.log(`Shipping: $${importCost.breakdown.shipping}`)
console.log(`Customs Duty (${importCost.duties?.rate}): $${importCost.breakdown.customsDuty}`)
console.log(`VAT: $${importCost.breakdown.vat}`)
console.log(`Brokerage: $${importCost.breakdown.brokerage}`)
console.log(`Other Fees: $${importCost.breakdown.otherFees}`)
console.log(`\nTotal Landed Cost: $${importCost.summary.totalLandedCost}`)
console.log(`\nClearance Time: ${importCost.shipping.clearanceTime}`)
console.log(`Required Documents: ${importCost.shipping.requiredDocuments.join(', ')}`)Output:
Import Cost Breakdown:
Product Value: $1200
Shipping: $850
Customs Duty (8%): $96
VAT: $97.20
Brokerage: $100
Other Fees: $75
Total Landed Cost: $2418.20
Clearance Time: 3-7 days
Required Documents: Commercial Invoice, Packing List, Bill of Lading / Air Waybill, Certificate of Origin, Customs Declaration FormFleet Management
Nearby vehicle search for dispatch optimization.
Driver Assignment
typescript
async function findNearestAvailableDriver(pickupLocation, vehicleType = 'SEDAN') {
// Search for nearby available drivers
const nearby = await client.realm.utilities.nearby.search({
location: pickupLocation,
radius: 5000, // 5km
vehicleType,
status: 'AVAILABLE',
limit: 5
})
if (nearby.count === 0) {
// Expand search radius
const expanded = await client.realm.utilities.nearby.search({
location: pickupLocation,
radius: 10000, // 10km
vehicleType,
status: 'AVAILABLE',
limit: 5
})
return expanded
}
return nearby
}
// Usage - Find driver for pickup
const pickupLocation = { lat: 5.6037, lng: -0.1870 }
const drivers = await findNearestAvailableDriver(pickupLocation, 'SEDAN')
console.log(`Found ${drivers.count} available drivers:`)
drivers.vehicles.forEach((driver, i) => {
console.log(`${i + 1}. Driver ${driver.id}`)
console.log(` Distance: ${(driver.distance / 1000).toFixed(2)} km`)
console.log(` ETA: ${Math.ceil(driver.distance / 500)} min`) // ~30 km/h average
})
// Assign to nearest driver
const nearestDriver = drivers.vehicles[0]
console.log(`\nAssigned to Driver ${nearestDriver.id}`)
console.log(`Pickup ETA: ${Math.ceil(nearestDriver.distance / 500)} min`)Route Planning
Distance and ETA calculation for route optimization.
Multi-Stop Route Calculation
typescript
async function calculateRouteDistance(stops) {
const distances = []
// Calculate distance between each consecutive pair of stops
for (let i = 0; i < stops.length - 1; i++) {
const distance = await client.realm.utilities.distance.calculate({
origin: stops[i],
destination: stops[i + 1],
mode: 'ROAD'
})
distances.push({
from: stops[i].city,
to: stops[i + 1].city,
distance: distance.distance.value,
miles: distance.distance.miles
})
}
const totalDistance = distances.reduce((sum, d) => sum + d.distance, 0)
return {
stops: distances,
totalDistance,
totalMiles: distances.reduce((sum, d) => sum + d.miles, 0)
}
}
// Usage - Lagos to Kano via Abuja
const stops = [
{ country: 'NG', city: 'Lagos', coordinates: [6.5244, 3.3792] },
{ country: 'NG', city: 'Abuja', coordinates: [9.0765, 7.3986] },
{ country: 'NG', city: 'Kano', coordinates: [12.0022, 8.5920] }
]
const route = await calculateRouteDistance(stops)
console.log('Route Plan:')
route.stops.forEach((leg, i) => {
console.log(`${i + 1}. ${leg.from} → ${leg.to}: ${leg.distance.toFixed(0)} km`)
})
console.log(`\nTotal Distance: ${route.totalDistance.toFixed(0)} km (${route.totalMiles.toFixed(0)} miles)`)Output:
Route Plan:
1. Lagos → Abuja: 472 km
2. Abuja → Kano: 356 km
Total Distance: 828 km (514 miles)Zone-Based Pricing
Service area determination for pricing.
Delivery Zone Check
typescript
async function checkDeliveryZone(address) {
// Assign zone
const zone = await client.realm.utilities.zone.assign({
location: address,
serviceType: 'DELIVERY'
})
// Get zone-specific pricing
const zonePricing = {
'ZONE_A': { baseFee: 500, perKm: 50 },
'ZONE_B': { baseFee: 800, perKm: 60 },
'ZONE_C': { baseFee: 1200, perKm: 80 }
}
const pricing = zonePricing[zone.zone.id] || zonePricing['ZONE_C']
return {
zone: zone.zone.name,
zoneId: zone.zone.id,
coverage: zone.coverage,
pricing: {
baseFee: pricing.baseFee,
perKmRate: pricing.perKm,
currency: 'NGN'
},
serviceAvailable: zone.zone.id in zonePricing
}
}
// Usage
const deliveryAddress = {
country: 'NG',
city: 'Lagos',
address: '1 Victoria Island, Lagos',
coordinates: [6.4281, 3.4219]
}
const zoneInfo = await checkDeliveryZone(deliveryAddress)
console.log('Delivery Zone Information:')
console.log(`Zone: ${zoneInfo.zone} (${zoneInfo.zoneId})`)
console.log(`Coverage: ${zoneInfo.coverage}`)
console.log(`Base Fee: ${zoneInfo.pricing.baseFee} ${zoneInfo.pricing.currency}`)
console.log(`Per KM: ${zoneInfo.pricing.perKmRate} ${zoneInfo.pricing.currency}`)
console.log(`Service Available: ${zoneInfo.serviceAvailable ? 'Yes' : 'No'}`)Webhook Integration
Use utilities in webhooks for event-driven calculations.
Order Created Webhook
typescript
import express from 'express'
const app = express()
// Webhook endpoint for order creation
app.post('/webhooks/order-created', async (req, res) => {
const { order } = req.body
try {
// Calculate shipping cost
const deliveryFee = await client.realm.utilities.delivery.calculate({
origin: order.warehouse,
destination: order.customer.address,
serviceLevel: order.shippingMethod,
weight: { value: order.totalWeight, unit: 'kg' }
})
// Update order with calculated fee
await updateOrder(order.id, {
shippingCost: deliveryFee.totalFee,
currency: deliveryFee.currency,
estimatedDelivery: deliveryFee.estimatedDeliveryTime
})
// Send confirmation email
await sendEmail(order.customer.email, {
subject: 'Order Confirmed',
shippingCost: `${deliveryFee.totalFee} ${deliveryFee.currency}`,
estimatedDelivery: `${deliveryFee.estimatedDeliveryTime.min.day}-${deliveryFee.estimatedDeliveryTime.max.day} days`
})
res.json({ success: true })
} catch (error) {
console.error('Webhook error:', error)
res.status(500).json({ error: error.message })
}
})Pipeline Integration
Use utilities in De. Pipelines for autonomous workflows.
Automated Fulfillment Pipeline
json
{
"name": "Smart Order Fulfillment",
"stages": [
{
"name": "Calculate Delivery Fee",
"action": "WEBHOOK",
"webhook": {
"url": "https://api.dedot.app/realm/utilities/fares/delivery",
"method": "POST",
"headers": {
"Authorization": "Bearer ${env.DE_API_KEY}",
"Content-Type": "application/json"
},
"body": {
"origin": "${execution.metadata.warehouse}",
"destination": "${execution.metadata.customer.address}",
"serviceLevel": "NEXT_DAY",
"weight": {
"value": "${execution.metadata.totalWeight}",
"unit": "kg"
}
}
},
"transitions": {
"onSuccess": {
"type": "CONTINUE",
"next": "Validate Zone"
}
}
},
{
"name": "Validate Zone",
"action": "WEBHOOK",
"webhook": {
"url": "https://api.dedot.app/realm/utilities/zone",
"method": "POST",
"body": {
"location": "${execution.metadata.customer.address}",
"serviceType": "DELIVERY"
}
},
"transitions": {
"onSuccess": {
"type": "CONTINUE",
"next": "Assign Carrier",
"condition": {
"field": "result.zone.coverage",
"operator": "EQUALS",
"value": "FULL"
}
},
"onFailure": {
"type": "SKIP",
"next": "Request Manual Review"
}
}
}
]
}Error Handling
Best practices for handling utility errors.
Graceful Degradation
typescript
async function calculateShippingWithFallback(request) {
try {
// Try to calculate with LSP integration
const result = await client.realm.utilities.delivery.calculate(request)
// Check confidence level
if (result.metadata.confidence < 0.70) {
console.warn('Low confidence calculation:', result.metadata.dataSource)
// Maybe show warning to user
}
return result
} catch (error) {
console.error('Primary calculation failed:', error)
// Fallback to simple distance-based estimate
const distance = await client.realm.utilities.distance.calculate({
origin: request.origin,
destination: request.destination,
mode: 'ROAD'
})
// Simple calculation: $2 per km
const estimate = {
totalFee: distance.distance.value * 2,
currency: 'USD',
breakdown: {
baseFee: 5,
distanceFee: distance.distance.value * 2 - 5
},
metadata: {
accuracy: 'ESTIMATE',
confidence: 0.50,
dataSource: 'FALLBACK',
calculatedAt: Date.now(),
disclaimer: 'Estimate only. Actual cost may vary.'
}
}
return estimate
}
}Performance Optimization
Optimize utility calls for high-volume scenarios.
Batch Calculations
typescript
async function calculateBulkShipping(orders) {
// Calculate all shipping costs in parallel
const results = await Promise.all(
orders.map(order =>
client.realm.utilities.delivery.calculate({
origin: order.warehouse,
destination: order.destination,
serviceLevel: order.serviceLevel,
weight: order.weight
})
)
)
return orders.map((order, i) => ({
orderId: order.id,
shippingCost: results[i].totalFee,
currency: results[i].currency,
confidence: results[i].metadata.confidence
}))
}
// Process 100 orders
const orders = getOrders({ status: 'pending', limit: 100 })
const shippingCosts = await calculateBulkShipping(orders)
console.log(`Calculated shipping for ${shippingCosts.length} orders`)Caching Results
typescript
const cache = new Map()
async function getCachedDeliveryFee(cacheKey, request) {
// Check cache
if (cache.has(cacheKey)) {
const cached = cache.get(cacheKey)
// Cache valid for 1 hour
if (Date.now() - cached.timestamp < 3600000) {
console.log('Cache hit')
return cached.result
}
}
// Calculate
const result = await client.realm.utilities.delivery.calculate(request)
// Cache result
cache.set(cacheKey, {
result,
timestamp: Date.now()
})
return result
}
// Usage with cache key
const cacheKey = `delivery:${origin.city}:${dest.city}:${weight}`
const fee = await getCachedDeliveryFee(cacheKey, request)Testing
Unit testing utilities in your application.
Mock Responses
typescript
import { jest } from '@jest/globals'
// Mock the SDK
jest.mock('@dedot/sdk', () => ({
DeClient: jest.fn().mockImplementation(() => ({
realm: {
utilities: {
delivery: {
calculate: jest.fn().mockResolvedValue({
totalFee: 8500,
currency: 'NGN',
breakdown: {
baseFee: 3000,
distanceFee: 4000,
weightFee: 1500
},
metadata: {
confidence: 0.92,
dataSource: 'LSP'
}
})
}
}
}
}))
}))
// Test
describe('Shipping Calculator', () => {
it('should calculate delivery fee correctly', async () => {
const result = await calculateShipping(mockOrder)
expect(result.totalFee).toBe(8500)
expect(result.currency).toBe('NGN')
expect(result.metadata.dataSource).toBe('LSP')
})
})
