@trackthatride/core
v1.0.0
Published
Core API client for Track That Ride SDK
Downloads
6
Maintainers
Readme
@trackthatride/core
Core API client for interacting with the Track That Ride platform. Provides type-safe methods for managing rides, drivers, and public tracking data.
Installation
npm install @trackthatride/coreQuick Start
import { createClient } from '@trackthatride/core';
const client = createClient({
apiKey: 'tk_live_abc123_def456',
baseUrl: 'https://your-app.replit.app'
});
// Fetch rides
const response = await client.getRides({ status: 'in_transit' });
console.log(response.data);Configuration
Required Configuration
const client = createClient({
apiKey: string; // Your Track That Ride API key
baseUrl: string; // Your Track That Ride API base URL (required)
});Optional Configuration
const client = new TrackThatRideClient({
apiKey: 'tk_live_...',
baseUrl: 'https://your-app.replit.app',
timeout: 30000, // Request timeout in milliseconds (default: 30000)
retryAttempts: 3, // Number of retry attempts on failure (default: 3)
enableLogging: true // Enable debug logging (default: false)
});API Reference
Rides API
Get Rides
Fetch a list of rides with optional filtering.
const response = await client.getRides({
status?: 'pending' | 'assigned' | 'in_transit' | 'delivered' | 'cancelled';
driverId?: number;
limit?: number;
offset?: number;
});
// Response: ApiResponse<Ride[]>Get Ride by ID
Fetch a specific ride by its ID.
const response = await client.getRide(rideId);
// Response: ApiResponse<Ride>Create Ride
Create a new ride.
const response = await client.createRide({
customer_name: 'John Doe',
phone_number: '+1234567890',
pickup_address: '123 Main St',
delivery_address: '456 Oak Ave',
notes: 'Handle with care'
});
// Response: ApiResponse<Ride>Update Ride
Update an existing ride.
const response = await client.updateRide(rideId, {
status: 'in_transit',
notes: 'Updated delivery instructions'
});
// Response: ApiResponse<Ride>Delete Ride
Delete a ride.
const response = await client.deleteRide(rideId);
// Response: ApiResponse<void>Drivers API
Get Drivers
Fetch a list of drivers with optional filtering.
const response = await client.getDrivers({
status?: 'available' | 'busy' | 'offline';
limit?: number;
offset?: number;
});
// Response: ApiResponse<Driver[]>Get Driver by ID
Fetch a specific driver by their ID.
const response = await client.getDriver(driverId);
// Response: ApiResponse<Driver>Public Tracking API
Get Public Ride Status
Fetch public tracking information for a ride using its tracking code. This endpoint does not require authentication and can be used for customer-facing tracking pages.
const response = await client.getPublicRideStatus('TR123456789');
// Response: ApiResponse<{
// ride: Ride;
// driver?: Driver;
// estimatedArrival?: string;
// currentLocation?: { latitude: number; longitude: number };
// }>Company API
Get Company Info
Fetch information about your company.
const response = await client.getCompanyInfo();
// Response: ApiResponse<Company>Health Check
Check API Health
Verify that the API is running and accessible.
const response = await client.healthCheck();
// Response: ApiResponse<{ status: string; timestamp: string }>Type Definitions
Ride
interface Ride {
id: number;
tracking_code: string;
customer_name: string;
phone_number: string;
pickup_address: string;
delivery_address: string;
pickup_latitude?: number;
pickup_longitude?: number;
delivery_latitude?: number;
delivery_longitude?: number;
status: 'pending' | 'assigned' | 'in_transit' | 'delivered' | 'cancelled';
driver_id?: number;
notes?: string;
companyId: number;
createdAt: string;
updatedAt?: string;
scheduledPickupTime?: string;
actualPickupTime?: string;
estimatedDeliveryTime?: string;
actualDeliveryTime?: string;
}Driver
interface Driver {
id: number;
firstName: string;
lastName: string;
email?: string;
mobileNumber: string;
licenseNumber?: string;
vehicleType?: string;
vehiclePlate?: string;
status: 'available' | 'busy' | 'offline';
latitude?: number;
longitude?: number;
companyId: number;
isVerified: boolean;
createdAt: string;
updatedAt?: string;
}Company
interface Company {
id: number;
name: string;
slug: string;
email: string;
phone?: string;
address?: string;
approved: boolean;
subscriptionTier: 'basic' | 'pro' | 'enterprise';
logo_url?: string;
createdAt: string;
updatedAt?: string;
}ApiResponse
All API methods return a response in this format:
interface ApiResponse<T = any> {
success: boolean;
data?: T;
error?: string;
message?: string;
}Error Handling
The SDK provides specialized error classes for different scenarios:
import {
SDKError,
AuthenticationError,
RateLimitError,
ValidationError
} from '@trackthatride/core';
try {
const response = await client.getRides();
} catch (error) {
if (error instanceof AuthenticationError) {
// Invalid API key (401)
console.error('Authentication failed:', error.message);
} else if (error instanceof RateLimitError) {
// Rate limit exceeded (429)
console.error('Too many requests:', error.message);
} else if (error instanceof ValidationError) {
// Invalid request data (400)
console.error('Validation error:', error.message, error.details);
} else if (error instanceof SDKError) {
// Other HTTP errors
console.error('API error:', error.statusCode, error.message);
} else {
// Network or unexpected errors
console.error('Unexpected error:', error);
}
}Error Classes
SDKError: Base error class for all SDK errors
message: Error descriptionstatusCode: HTTP status code (if applicable)code: Error code identifierdetails: Additional error details
AuthenticationError: API key is invalid or missing (401)
RateLimitError: Too many requests (429)
ValidationError: Request validation failed (400)
- Includes
detailsproperty with validation error information
- Includes
Response Handling
All API responses follow a consistent structure:
// Success response
{
success: true,
data: { /* response data */ }
}
// Error response
{
success: false,
error: 'Error message',
message: 'Additional details'
}Checking Response Status
const response = await client.getRides();
if (response.success && response.data) {
// Handle successful response
response.data.forEach(ride => {
console.log(ride.tracking_code);
});
} else {
// Handle error
console.error('Error:', response.error || response.message);
}Advanced Usage
Custom Request Timeout
const client = new TrackThatRideClient({
apiKey: 'tk_live_...',
baseUrl: 'https://your-app.replit.app',
timeout: 60000 // 60 seconds
});Enable Debug Logging
const client = new TrackThatRideClient({
apiKey: 'tk_live_...',
baseUrl: 'https://your-app.replit.app',
enableLogging: true // Logs all requests and responses
});Retry Configuration
const client = new TrackThatRideClient({
apiKey: 'tk_live_...',
baseUrl: 'https://your-app.replit.app',
retryAttempts: 5 // Retry failed requests up to 5 times
});Best Practices
Store API Keys Securely: Never commit API keys to version control. Use environment variables.
const client = createClient({ apiKey: process.env.TRACKTHATRIDE_API_KEY, baseUrl: process.env.TRACKTHATRIDE_BASE_URL });Handle Errors Gracefully: Always wrap API calls in try-catch blocks.
Use Type Safety: The SDK provides full TypeScript support. Use the exported types for better development experience.
Implement Rate Limiting: Be mindful of rate limits and implement appropriate backoff strategies.
Enable Logging in Development: Use
enableLogging: trueduring development to debug API interactions.
TypeScript Support
This package is written in TypeScript and includes type definitions. All types are automatically available when using TypeScript:
import { Ride, Driver, Company, ApiResponse } from '@trackthatride/core';
const processRide = (ride: Ride): void => {
console.log(`Processing delivery for ${ride.customer_name}`);
};License
MIT
Support
For support, please contact Track That Ride support or visit our documentation at /docs on your Track That Ride instance.
