@voltade/plato-sdk
v1.0.5
Published
A comprehensive TypeScript SDK for the Plato Medical API with built-in rate limiting, error handling, and resource-based architecture
Readme
@voltade/plato-sdk
A comprehensive, type-safe TypeScript SDK for the Plato Medical API with built-in rate limiting, error handling, and resource-based architecture.
Features
- 🎯 Resource-based API: Organized by resource type (Patients, Appointments, Invoices)
- 🔒 Type-safe: Full TypeScript support with comprehensive type definitions
- ⚡ Rate Limiting: Optional built-in rate limiting to respect API limits
- 🚨 Error Handling: Comprehensive error classes for different failure scenarios
- 📄 Pagination Support: Built-in pagination utilities for list operations
- 🌐 Modern HTTP Client: Uses native fetch with timeout and error handling
- 📚 Well Documented: Extensive JSDoc documentation and usage examples
Installation
Note: This package is published to GitHub Packages (not npm) as a private package.
Prerequisites
- Install the package:
npm install @voltade/plato-sdkyarn add @voltade/plato-sdkpnpm add @voltade/plato-sdkQuick Start
import { PlatoClient } from "@voltade/plato-sdk";
// Initialize the client
const client = new PlatoClient({
apiKey: "your-api-key", // Optional if PLATO_API_KEY env var is set
dbName: "your-db-name", // Optional if PLATO_DB_NAME env var is set
useRateLimit: true, // Enable rate limiting (default: false)
timeout: 30000, // Request timeout in ms (default: 30000)
});
// Create a patient
const patient = await client.patients.create({
name: "John Doe",
email: "[email protected]",
telephone: "12345678",
});
// Get available appointment slots
const slots = await client.appointments.getSlots({
date: "2024-03-15",
calendarId: "ABC123",
});
// Get today's invoices
const invoices = await client.invoices.getToday();Configuration
Environment Variables
The SDK can be configured using environment variables:
PLATO_API_KEY=your-api-key
PLATO_DB_NAME=your-db-nameClient Options
interface PlatoClientConfig {
apiKey?: string; // API key (default: process.env.PLATO_API_KEY)
dbName?: string; // Database name (default: process.env.PLATO_DB_NAME)
baseUrl?: string; // Base URL (default: https://clinic.platomedical.com/api)
useRateLimit?: boolean; // Enable rate limiting (default: false)
timeout?: number; // Request timeout in ms (default: 30000)
}API Reference
Patients
Create a Patient
const patient = await client.patients.create({
name: "John Doe",
email: "[email protected]",
telephone: "12345678",
gender: "Male",
dob: "1990-01-01",
address: "123 Main St",
postal: "123456",
});Find or Create Patient
// This will find an existing patient or create a new one
const patient = await client.patients.createOrFind({
name: "John Doe",
email: "[email protected]",
telephone: "12345678",
});Search for Patients
const patients = await client.patients.search({
name: "John",
telephone: "12345678",
});List Patients
const patients = await client.patients.list({
skip: 0,
current_page: 1,
start_date: "2024-01-01",
end_date: "2024-12-31",
});Update a Patient
const updated = await client.patients.update("patient-id", {
email: "[email protected]",
});Delete a Patient
await client.patients.delete("patient-id");Appointments
Get Available Slots
const slots = await client.appointments.getSlots({
date: "2024-03-15",
calendarId: "ABC123",
starttime: "09:00", // Optional (default: 10:00)
endtime: "18:00", // Optional (default: 20:00)
interval: 30, // Optional (default: 30 minutes)
});
// Returns: ['09:00', '09:30', '10:00', ...]Create an Appointment
const appointment = await client.appointments.create({
patient_id: "patient-id",
title: "John Doe - Consultation",
starttime: "2024-03-15 10:00:00",
endtime: "2024-03-15 11:00:00",
color: "ABC123", // Calendar ID
description: "Initial consultation",
});List Appointments
const appointments = await client.appointments.list({
start_date: "2024-03-01",
end_date: "2024-03-31",
});Update an Appointment
const updated = await client.appointments.update("appointment-id", {
starttime: "2024-03-15 11:00:00",
description: "Updated time",
});Delete an Appointment
await client.appointments.delete("appointment-id");Invoices
Get Today's Invoices
const invoices = await client.invoices.getToday();Get Invoices by Date
const invoices = await client.invoices.getByDate("2024-03-15");Get Invoices by Date Range
const invoices = await client.invoices.getByDateRange(
"2024-03-01",
"2024-03-31"
);Create an Invoice
const invoice = await client.invoices.create({
date: "2024-03-15",
patient_id: "patient-id",
invoice: "INV-001",
item: [
{
given_id: "ITEM-001",
name: "Consultation",
qty: 1,
unit_price: 100,
discount: 0,
},
],
});List Invoices
const invoices = await client.invoices.list({
start_date: "2024-03-01",
end_date: "2024-03-31",
});Error Handling
The SDK provides specific error classes for different failure scenarios:
import {
PlatoError,
AuthenticationError,
BadRequestError,
NotFoundError,
RateLimitError,
ServerError,
NetworkError,
} from "@voltade/plato-sdk";
try {
const patient = await client.patients.get("invalid-id");
} catch (error) {
if (error instanceof NotFoundError) {
console.log("Patient not found");
} else if (error instanceof AuthenticationError) {
console.log("Invalid API credentials");
} else if (error instanceof RateLimitError) {
console.log(`Rate limit exceeded. Retry after ${error.retryAfter} seconds`);
} else if (error instanceof NetworkError) {
console.log("Network error occurred");
} else if (error instanceof PlatoError) {
console.log("Plato API error:", error.message);
}
}Available Error Classes
PlatoError- Base error class for all Plato API errorsAuthenticationError- 401 UnauthorizedBadRequestError- 400 Bad RequestNotFoundError- 404 Not FoundRateLimitError- 429 Too Many Requests (includesretryAfterproperty)ServerError- 5xx Server ErrorsNetworkError- Network/timeout errorsValidationError- Request validation errors
Rate Limiting
When rate limiting is enabled, the SDK automatically tracks the API's rate limit headers and waits when necessary:
const client = new PlatoClient({
useRateLimit: true,
});
// The SDK will automatically wait if rate limit is exhausted
const patients = await client.patients.list();
// Check rate limit status
const status = client.getRateLimitStatus();
console.log(status);
// {
// remaining: 45,
// limit: 50,
// lastResetTime: Date
// }TypeScript Support
All types are exported and fully documented:
import type {
Patient,
CreatePatientParams,
UpdatePatientParams,
Appointment,
CreateAppointmentParams,
Invoice,
InvoiceItem,
PaginationParams,
DateRangeParams,
} from "@voltade/plato-sdk";Advanced Usage
Direct Resource Access
import { Patients, HttpClient } from "@voltade/plato-sdk";
const httpClient = new HttpClient({
apiKey: "your-key",
dbName: "your-db",
});
const patients = new Patients(httpClient);
const patient = await patients.findByPhone("12345678");Custom HTTP Client
const httpClient = client.getHttpClient();
// Make custom requests
const response = await httpClient.get("/custom-endpoint", {
params: { key: "value" },
});Best Practices
- Always use rate limiting in production: Enable
useRateLimit: trueto respect API limits - Handle errors appropriately: Use specific error classes to handle different failure scenarios
- Use environment variables: Store API credentials in environment variables
- Leverage TypeScript: The SDK is fully typed for better developer experience
- Use pagination: For list operations, use pagination parameters to manage large datasets
Requirements
- Node.js >= 18.0.0
- TypeScript >= 5.0.0
Architecture
@voltade/plato-sdk/
├── client.ts # Main PlatoClient class
├── http-client.ts # HTTP client with error handling
├── rate-limiter.ts # Rate limiting logic
├── errors.ts # Error classes
├── types.ts # TypeScript type definitions
├── resources/
│ ├── base.ts # Base resource class
│ ├── patients.ts # Patient resource
│ ├── appointments.ts # Appointment resource
│ └── invoices.ts # Invoice resource
└── utils/
└── pagination.ts # Pagination utilitiesPublishing (Maintainers Only)
This package is published exclusively to GitHub Packages. To publish a new version:
1. Create a GitHub Personal Access Token
- Go to https://github.com/settings/tokens/new
- Name:
npm-publish-token - Select scopes:
write:packages,read:packages, andrepo - Generate and copy the token
2. Authenticate with GitHub Packages
npm login --registry=https://npm.pkg.github.com- Username:
voltade - Password: Your personal access token
- Email: Your GitHub email
3. Publish
# Bump version in package.json first
npm version patch # or minor, or major
# Publish to GitHub Packages
npm publishNote: This package is NOT published to npm, only to GitHub Packages.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
MIT © Voltade
Support
For issues and questions, please file an issue on GitHub.
Related Links
Made with ❤️ by Voltade
