Integration Guide
Step-by-step guide to integrating De. Queries into your logistics application.
Prerequisites
Before integrating De. Queries, ensure you have:
- De. Workspace - Active workspace with Queries service enabled
- Authentication - Valid API credentials (see Authentication Guide)
- SDK Installed - De. SDK for your platform
- Services Configured - At least one LSP with registered services (warehouses, carriers, etc.)
Quick Start (10 minutes)
Let's build a simple warehouse discovery feature.
Step 1: Initialize SDK
typescript
import { DeClient } from '@dedot/sdk'
const client = new DeClient({
apiKey: process.env.DE_API_KEY,
workspace: process.env.DE_WORKSPACE_ID
})
// Verify connection
const health = await client.health()
console.log('Connected to De.:', health.status)Step 2: Discover Nearby Warehouses
typescript
// Find warehouses within 50km of customer location
const result = await client.realm.queries.discovery.discover({
serviceType: 'WAREHOUSE',
location: {
coordinates: [40.7128, -74.0060], // New York City
maxDistance: 50 // km
}
})
console.log(`Found ${result.total} warehouses`)
result.services.forEach(warehouse => {
console.log(`- ${warehouse.name} (${warehouse.distance}km away)`)
})Expected Output:
Found 3 warehouses
- Manhattan Fulfillment Center (2.5km away)
- Brooklyn Distribution Hub (8.3km away)
- Queens Warehouse (15.7km away)Step 3: Filter by Capabilities
typescript
// Find cold chain warehouses
const coldChainWarehouses = await client.realm.queries.discovery.advancedDiscover({
serviceType: 'WAREHOUSE',
location: {
coordinates: [40.7128, -74.0060],
maxDistance: 100
},
capabilities: {
environmental: {
temperatureControlled: true,
temperatureRange: { min: -20, max: 5 }
}
}
})
console.log(`Found ${coldChainWarehouses.total} cold chain warehouses`)Step 4: Match Order to Warehouse
typescript
// Intelligently match order to best warehouse
const match = await client.realm.queries.matching.match({
serviceTypes: ['WAREHOUSE'],
delivery: {
country: 'US',
city: 'New York',
coordinates: [40.7128, -74.0060]
},
items: [
{ sku: 'PROD-001', quantity: 10, requiresColdChain: true },
{ sku: 'PROD-002', quantity: 5, weight: 2.5 }
],
requirements: ['COLD_CHAIN', 'SAME_DAY_DELIVERY'],
strategy: 'BALANCED'
})
const bestWarehouse = match.recommendations[0]
console.log('Best warehouse:', bestWarehouse.service.name)
console.log('Overall score:', bestWarehouse.scores.overall)
console.log('Capability score:', bestWarehouse.scores.capability)
console.log('Proximity score:', bestWarehouse.scores.proximity)You're done! You've integrated basic De. Queries. Continue below for advanced features.
Complete Integration Example
Here's a production-ready service for order fulfillment:
typescript
import { DeClient } from '@dedot/sdk'
interface Order {
id: string
items: Array<{
sku: string
quantity: number
weight?: number
requiresColdChain?: boolean
requiresHazmatHandling?: boolean
}>
deliveryAddress: {
lat: number
lng: number
city: string
country: string
zip: string
}
requirements?: string[]
priority: 'LOW' | 'NORMAL' | 'HIGH'
}
interface FulfillmentPlan {
order: Order
warehouse: {
id: string
name: string
distance: number
scores: MatchScores
}
carrier?: {
id: string
name: string
}
estimatedCost: number
estimatedDeliveryTime: Date
}
class OrderFulfillmentService {
private client: DeClient
constructor(apiKey: string, workspaceId: string) {
this.client = new DeClient({ apiKey, workspace: workspaceId })
}
async createFulfillmentPlan(order: Order): Promise<FulfillmentPlan> {
// Step 1: Find optimal warehouse using intelligent matching
const warehouseMatch = await this.findOptimalWarehouse(order)
if (!warehouseMatch) {
throw new Error('No suitable warehouse found for order')
}
// Step 2: Check warehouse capacity
const hasCapacity = await this.verifyCapacity(
warehouseMatch.service.lsp,
warehouseMatch.service.serviceId,
order.items.length
)
if (!hasCapacity) {
// Try next best warehouse
return this.createFulfillmentPlan(order) // Recursive with fallback
}
// Step 3: Assign carrier for delivery
const carrier = await this.assignCarrier(
warehouseMatch.service,
order.deliveryAddress
)
// Step 4: Estimate total cost
const cost = await this.estimateCost(
warehouseMatch.service,
carrier,
order
)
// Step 5: Calculate estimated delivery time
const deliveryTime = this.calculateDeliveryTime(
warehouseMatch.service,
carrier,
order
)
return {
order,
warehouse: {
id: warehouseMatch.service.serviceId,
name: warehouseMatch.service.name,
distance: warehouseMatch.service.distance || 0,
scores: warehouseMatch.scores
},
carrier: carrier ? {
id: carrier.serviceId,
name: carrier.name
} : undefined,
estimatedCost: cost,
estimatedDeliveryTime: deliveryTime
}
}
private async findOptimalWarehouse(order: Order) {
// Determine matching strategy based on priority
const strategy = this.getStrategyForPriority(order.priority)
// Build requirements from order
const requirements = [
...order.requirements || [],
...order.items
.filter(item => item.requiresColdChain)
.map(() => 'COLD_CHAIN'),
...order.items
.filter(item => item.requiresHazmatHandling)
.map(() => 'HAZMAT_HANDLING')
]
// Match order to warehouse
const match = await this.client.realm.queries.matching.match({
serviceTypes: ['WAREHOUSE'],
delivery: {
country: order.deliveryAddress.country,
city: order.deliveryAddress.city,
coordinates: [order.deliveryAddress.lat, order.deliveryAddress.lng]
},
items: order.items,
requirements: [...new Set(requirements)], // Remove duplicates
strategy
})
return match.recommendations[0]
}
private async verifyCapacity(
lsp: string,
serviceId: string,
requiredSlots: number
): Promise<boolean> {
try {
const capacity = await this.client.realm.queries.capacity.query({
lsp,
serviceId,
capacityType: 'STORAGE_SLOTS'
})
return capacity.available >= requiredSlots
} catch (error) {
console.warn('Capacity check failed:', error)
return true // Assume capacity if check fails
}
}
private async assignCarrier(
warehouse: any,
deliveryAddress: Order['deliveryAddress']
) {
try {
const match = await this.client.realm.queries.matching.match({
serviceTypes: ['CARRIER'],
delivery: {
country: deliveryAddress.country,
city: deliveryAddress.city,
coordinates: [deliveryAddress.lat, deliveryAddress.lng]
},
strategy: 'SPEED_OPTIMIZED'
})
return match.recommendations[0]?.service
} catch (error) {
console.warn('Carrier assignment failed:', error)
return null
}
}
private async estimateCost(
warehouse: any,
carrier: any,
order: Order
): Promise<number> {
try {
// Get warehouse fulfillment cost
const warehouseCost = await this.client.realm.queries.pricing.estimate({
lsp: warehouse.lsp,
serviceId: warehouse.serviceId,
serviceType: 'WAREHOUSE',
orderContext: {
items: order.items,
requirements: order.requirements,
deliveryLocation: {
country: order.deliveryAddress.country,
city: order.deliveryAddress.city
}
}
})
// Get carrier delivery cost if assigned
let carrierCost = 0
if (carrier) {
const carrierEstimate = await this.client.realm.queries.pricing.estimate({
lsp: carrier.lsp,
serviceId: carrier.serviceId,
serviceType: 'CARRIER',
orderContext: {
items: order.items,
deliveryLocation: {
country: order.deliveryAddress.country,
city: order.deliveryAddress.city
}
}
})
carrierCost = carrierEstimate.totalCost
}
return warehouseCost.totalCost + carrierCost
} catch (error) {
console.warn('Cost estimation failed:', error)
return 0
}
}
private calculateDeliveryTime(
warehouse: any,
carrier: any,
order: Order
): Date {
// Simple estimation based on priority
const hoursToAdd = order.priority === 'HIGH' ? 4 : order.priority === 'NORMAL' ? 24 : 48
return new Date(Date.now() + hoursToAdd * 3600000)
}
private getStrategyForPriority(priority: Order['priority']) {
switch (priority) {
case 'HIGH':
return 'SPEED_OPTIMIZED'
case 'NORMAL':
return 'BALANCED'
case 'LOW':
return 'COST_OPTIMIZED'
}
}
}
// Usage
const service = new OrderFulfillmentService(
process.env.DE_API_KEY!,
process.env.DE_WORKSPACE_ID!
)
const order: Order = {
id: 'ORD-12345',
items: [
{ sku: 'WIDGET-001', quantity: 10, weight: 0.5, requiresColdChain: true },
{ sku: 'GADGET-002', quantity: 5, weight: 1.2 }
],
deliveryAddress: {
lat: 40.7128,
lng: -74.0060,
city: 'New York',
country: 'US',
zip: '10001'
},
requirements: ['SAME_DAY_DELIVERY'],
priority: 'HIGH'
}
const plan = await service.createFulfillmentPlan(order)
console.log('Fulfillment Plan:', plan)Advanced Features
Dynamic Query Filters
Use variables and expressions in filters:
typescript
// Filter based on current date/time
const result = await client.realm.queries.discovery.discover({
serviceType: 'WAREHOUSE',
filters: {
'serviceLevel.orderProcessing.enabled': true,
'serviceLevel.orderProcessing.cutoffTime': {
$gt: new Date().getHours() // Still accepting orders
}
}
})Fallback Strategies
Handle cases when primary query returns no results:
typescript
async function findWarehouseWithFallback(location: [number, number]) {
// Try primary: Cold chain warehouses within 50km
let result = await client.realm.queries.discovery.discover({
serviceType: 'WAREHOUSE',
location: { coordinates: location, maxDistance: 50 },
capabilities: {
environmental: { temperatureControlled: true }
}
})
if (result.services.length === 0) {
// Fallback 1: Expand radius to 100km
result = await client.realm.queries.discovery.discover({
serviceType: 'WAREHOUSE',
location: { coordinates: location, maxDistance: 100 },
capabilities: {
environmental: { temperatureControlled: true }
}
})
}
if (result.services.length === 0) {
// Fallback 2: Remove cold chain requirement
result = await client.realm.queries.discovery.discover({
serviceType: 'WAREHOUSE',
location: { coordinates: location, maxDistance: 100 }
})
}
return result.services[0]
}Caching Strategy
Implement client-side caching for frequently accessed data:
typescript
class CachedQueryService {
private cache = new Map<string, { data: any; timestamp: number }>()
private cacheDuration = 300000 // 5 minutes
async discoverWithCache(criteria: QueryCriteria) {
const cacheKey = JSON.stringify(criteria)
const cached = this.cache.get(cacheKey)
if (cached && Date.now() - cached.timestamp < this.cacheDuration) {
return cached.data
}
const result = await client.realm.queries.discovery.discover(criteria)
this.cache.set(cacheKey, { data: result, timestamp: Date.now() })
return result
}
invalidateCache(criteria?: QueryCriteria) {
if (criteria) {
this.cache.delete(JSON.stringify(criteria))
} else {
this.cache.clear()
}
}
}Batch Operations
Query multiple services efficiently:
typescript
// Check capacity for multiple warehouses in parallel
const capacityChecks = await Promise.all([
client.realm.queries.capacity.query({
lsp: 'lsp-001',
serviceId: 'warehouse-123',
capacityType: 'STORAGE_SLOTS'
}),
client.realm.queries.capacity.query({
lsp: 'lsp-001',
serviceId: 'warehouse-456',
capacityType: 'STORAGE_SLOTS'
}),
client.realm.queries.capacity.query({
lsp: 'lsp-002',
serviceId: 'warehouse-789',
capacityType: 'STORAGE_SLOTS'
})
])
// Or use batch query endpoint
const batchResult = await client.realm.queries.capacity.batchQuery({
queries: [
{ lsp: 'lsp-001', serviceId: 'warehouse-123', capacityType: 'STORAGE_SLOTS' },
{ lsp: 'lsp-001', serviceId: 'warehouse-456', capacityType: 'STORAGE_SLOTS' },
{ lsp: 'lsp-002', serviceId: 'warehouse-789', capacityType: 'PALLET_POSITIONS' }
]
})Performance Monitoring
Track query performance and service health:
typescript
async function monitorServicePerformance() {
// Get performance for all warehouses
const warehouses = await client.realm.queries.discovery.discover({
serviceType: 'WAREHOUSE'
})
const performanceReports = await Promise.all(
warehouses.services.map(async warehouse => {
try {
const performance = await client.realm.queries.performance.get({
lsp: warehouse.lsp,
serviceId: warehouse.serviceId
})
return {
warehouse: warehouse.name,
performance: {
onTimeRate: performance.onTimeDeliveryRate,
accuracy: performance.orderAccuracy,
score: performance.overallScore
}
}
} catch (error) {
return {
warehouse: warehouse.name,
performance: null,
error: error.message
}
}
})
)
// Filter underperforming services
const underperforming = performanceReports.filter(
r => r.performance && r.performance.score < 70
)
if (underperforming.length > 0) {
console.warn('Underperforming services:', underperforming)
}
return performanceReports
}Error Handling
Implement robust error handling:
typescript
async function safeQuery(criteria: QueryCriteria) {
try {
const result = await client.realm.queries.discovery.discover(criteria)
if (result.services.length === 0) {
console.warn('No services found matching criteria')
// Implement fallback logic
}
return result
} catch (error) {
if (error.code === 'UNAUTHORIZED') {
console.error('Authentication failed - check API key')
// Refresh credentials
} else if (error.code === 'RATE_LIMIT_EXCEEDED') {
console.warn('Rate limit exceeded - implementing backoff')
await new Promise(resolve => setTimeout(resolve, 5000))
return safeQuery(criteria) // Retry
} else if (error.code === 'SERVICE_UNAVAILABLE') {
console.error('Service temporarily unavailable')
// Use cached data or fallback
} else {
console.error('Query failed:', error)
}
throw error
}
}Testing Queries
Unit Tests
typescript
import { describe, it, expect, beforeAll } from '@jest/globals'
import { DeClient } from '@dedot/sdk'
describe('De. Queries', () => {
let client: DeClient
beforeAll(() => {
client = new DeClient({
apiKey: process.env.TEST_API_KEY,
workspace: process.env.TEST_WORKSPACE_ID
})
})
describe('Discovery', () => {
it('should find warehouses within specified radius', async () => {
const result = await client.realm.queries.discovery.discover({
serviceType: 'WAREHOUSE',
location: {
coordinates: [40.7128, -74.0060],
maxDistance: 50
}
})
expect(result.services).toBeDefined()
expect(result.total).toBeGreaterThan(0)
expect(result.services.every(s => s.distance! <= 50)).toBe(true)
})
it('should filter by capabilities', async () => {
const result = await client.realm.queries.discovery.advancedDiscover({
serviceType: 'WAREHOUSE',
capabilities: {
environmental: { temperatureControlled: true }
}
})
expect(result.services.every(s =>
s.capabilities?.environmental?.temperatureControlled === true
)).toBe(true)
})
})
describe('Matching', () => {
it('should match order to optimal warehouse', async () => {
const match = await client.realm.queries.matching.match({
serviceTypes: ['WAREHOUSE'],
delivery: {
country: 'US',
city: 'New York',
coordinates: [40.7128, -74.0060]
},
items: [{ sku: 'TEST-001', quantity: 1 }],
strategy: 'BALANCED'
})
expect(match.recommendations).toBeDefined()
expect(match.recommendations.length).toBeGreaterThan(0)
expect(match.recommendations[0].scores.overall).toBeGreaterThan(0)
})
})
describe('Capacity', () => {
it('should query warehouse capacity', async () => {
const capacity = await client.realm.queries.capacity.query({
lsp: 'test-lsp',
serviceId: 'warehouse-001',
capacityType: 'STORAGE_SLOTS'
})
expect(capacity).toBeDefined()
expect(capacity.total).toBeGreaterThan(0)
expect(capacity.available).toBeGreaterThanOrEqual(0)
})
})
})Production Best Practices
1. Connection Pooling
typescript
// Reuse client instance across requests
let client: DeClient
export function getClient() {
if (!client) {
client = new DeClient({
apiKey: process.env.DE_API_KEY,
workspace: process.env.DE_WORKSPACE_ID
})
}
return client
}2. Rate Limiting
typescript
import pLimit from 'p-limit'
// Limit concurrent queries
const limit = pLimit(10)
const results = await Promise.all(
warehouses.map(w =>
limit(() => client.realm.queries.capacity.query({
lsp: w.lsp,
serviceId: w.serviceId,
capacityType: 'STORAGE_SLOTS'
}))
)
)3. Monitoring & Alerting
typescript
// Track query performance
const startTime = Date.now()
const result = await client.realm.queries.discovery.discover(criteria)
const duration = Date.now() - startTime
if (duration > 1000) {
console.warn(`Slow query detected: ${duration}ms`)
// Send alert to monitoring system
}
// Track success/failure rates
metrics.increment('queries.discovery.total')
if (result.services.length > 0) {
metrics.increment('queries.discovery.success')
} else {
metrics.increment('queries.discovery.no_results')
}4. Graceful Degradation
typescript
async function findWarehouseWithGracefulDegradation(location: [number, number]) {
try {
// Try intelligent matching first
const match = await client.realm.queries.matching.match({
serviceTypes: ['WAREHOUSE'],
delivery: { coordinates: location },
strategy: 'BALANCED'
})
if (match.recommendations.length > 0) {
return match.recommendations[0].service
}
} catch (error) {
console.warn('Matching service unavailable, falling back to discovery')
}
try {
// Fallback to basic discovery
const result = await client.realm.queries.discovery.discover({
serviceType: 'WAREHOUSE',
location: { coordinates: location, maxDistance: 100 }
})
if (result.services.length > 0) {
return result.services[0]
}
} catch (error) {
console.error('All query methods failed:', error)
}
// Last resort: return hardcoded default
return DEFAULT_WAREHOUSE
}
