@datacanvas/sdk
v1.0.1
Published
Official Node.js SDK for DataCanvas IoT Platform - A modern, type-safe, resource-based client library
Readme
DataCanvas SDK for Node.js
Official Node.js SDK for the DataCanvas IoT Platform. A modern, type-safe, and resource-based client library for seamless integration with DataCanvas API.
✨ Features
- 🎯 Resource-Based Architecture - Intuitive API organized by domain concepts
- 🔒 Type-Safe - Full TypeScript support with comprehensive type definitions
- ⚡ Modern - Built with ES2020+, supports both ESM and CommonJS
- 🛡️ Robust Error Handling - Comprehensive error hierarchy for precise error management
- 📦 Zero Dependencies - Uses native
fetchAPI for minimal bundle size
📦 Installation
npm install @datacanvas/sdkyarn add @datacanvas/sdkpnpm add @datacanvas/sdk🚀 Quick Start
TypeScript / ES Modules
import { DataCanvas, SortOrder } from '@datacanvas/sdk';
// Initialize SDK with default API endpoint
const client = new DataCanvas({
access_key_client: process.env.DATACANVAS_ACCESS_KEY_ID!,
access_key_secret: process.env.DATACANVAS_SECRET_KEY!,
projectId: parseInt(process.env.DATACANVAS_PROJECT_ID!),
});
// Or with a custom base URL (optional)
const customClient = new DataCanvas({
access_key_client: process.env.DATACANVAS_ACCESS_KEY_ID!,
access_key_secret: process.env.DATACANVAS_SECRET_KEY!,
projectId: parseInt(process.env.DATACANVAS_PROJECT_ID!),
baseUrl: 'https://api.<something>.<something>', // Optional: for regional endpoints or self-hosted instances
});
// List all devices
const devices = await client.devices.list();
console.log(`Found ${devices.devices.length} devices`);
// Retrieve data from a datatable
const data = await client.data.list({
tableName: 'temperature_sensors',
deviceIds: [1, 2, 3],
page: 0,
limit: 50,
order: SortOrder.DESC,
});
console.log(`Retrieved ${data.count} data points`);JavaScript / CommonJS
const { DataCanvas, SortOrder } = require('@datacanvas/sdk');
// Initialize SDK with default API endpoint
const client = new DataCanvas({
access_key_client: process.env.DATACANVAS_ACCESS_KEY_ID,
access_key_secret: process.env.DATACANVAS_SECRET_KEY,
projectId: parseInt(process.env.DATACANVAS_PROJECT_ID),
});
// Or with a custom base URL (optional)
const customClient = new DataCanvas({
access_key_client: process.env.DATACANVAS_ACCESS_KEY_ID,
access_key_secret: process.env.DATACANVAS_SECRET_KEY,
projectId: parseInt(process.env.DATACANVAS_PROJECT_ID),
baseUrl: 'https://api.<something>.<something>', // Optional
});
// Use async/await in an async function
async function main() {
const devices = await client.devices.list();
console.log(`Found ${devices.devices.length} devices`);
}
main().catch(console.error);📚 API Reference
Configuration
new DataCanvas(config: SDKConfig)
Creates a new SDK instance with the provided configuration.
Parameters:
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| access_key_client | string | ✅ | Client access key ID from DataCanvas dashboard |
| access_key_secret | string | ✅ | Secret access key for authentication |
| projectId | number | ✅ | Project ID to scope API requests |
| baseUrl | string | ❌ | Custom API base URL (defaults to standard DataCanvas endpoint) |
Example:
// Using default API endpoint
const client = new DataCanvas({
access_key_client: 'your-access-key-id',
access_key_secret: 'your-secret-key',
projectId: 123,
});
// Using custom API endpoint (for testing or self-hosted instances)
const customClient = new DataCanvas({
access_key_client: 'your-access-key-id',
access_key_secret: 'your-secret-key',
projectId: 123,
baseUrl: 'https://custom.<something>.<something>/api',
});Device Management
client.devices.list(): Promise<DeviceResponse>
Retrieves all devices associated with the configured project.
Returns: Promise<DeviceResponse>
Example:
const response = await client.devices.list();
response.devices.forEach(device => {
console.log(`Device: ${device.device_name} (ID: ${device.device_id})`);
});Response Type:
interface DeviceResponse {
success: boolean;
devices: Device[];
}
interface Device {
device_id: number;
device_name: string;
}Data Retrieval
client.data.list(params: GetDataParams): Promise<DataResponse>
Retrieves data from a specified datatable with optional filtering and pagination.
Parameters:
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| tableName | string | ✅ | - | Name of the datatable to query |
| deviceIds | number[] | ❌ | [] | Array of device IDs to filter |
| page | number | ❌ | 0 | Page number (0-indexed) |
| limit | number | ❌ | 20 | Items per page (max: 1000) |
| order | SortOrder | ❌ | DESC | Sort order (ASC or DESC) |
Returns: Promise<DataResponse>
Example:
import { SortOrder } from '@datacanvas/sdk';
// Retrieve all data
const allData = await client.data.list({
tableName: 'temperature_sensors',
});
// Retrieve with filtering and pagination
const filteredData = await client.data.list({
tableName: 'temperature_sensors',
deviceIds: [1, 2, 3],
page: 0,
limit: 50,
order: SortOrder.DESC,
});
console.log(`Total records: ${filteredData.count}`);
// Process data by device
Object.entries(filteredData.data).forEach(([deviceId, dataPoints]) => {
console.log(`Device ${deviceId}: ${dataPoints.length} data points`);
dataPoints.forEach(point => {
console.log(` - Value: ${point.value}, Timestamp: ${point.timestamp}`);
});
});Response Type:
interface DataResponse {
count: number;
data: Record<string, DataPoint[]>;
}
interface DataPoint {
id: number;
device: number;
[key: string]: any; // Dynamic fields from datatable schema
}🛡️ Error Handling
The SDK provides comprehensive error handling with specific error types for different scenarios.
Error Types
| Error Class | Description | HTTP Status |
|-------------|-------------|-------------|
| AuthenticationError | Invalid credentials | 401 |
| AuthorizationError | Insufficient permissions | 403 |
| ValidationError | Invalid request parameters | 400, 422 |
| NotFoundError | Resource not found | 404 |
| RateLimitError | Rate limit exceeded | 429 |
| ServerError | Server-side error | 500+ |
| NetworkError | Network connectivity issue | - |
Handling Errors
import {
DataCanvas,
AuthenticationError,
ValidationError,
RateLimitError,
NetworkError,
} from '@datacanvas/sdk';
try {
const data = await client.data.list({
tableName: 'sensors',
limit: 100,
});
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Authentication failed. Check your credentials.');
// Redirect to login or refresh tokens
} else if (error instanceof ValidationError) {
console.error('Invalid request:', error.message);
// Show validation error to user
} else if (error instanceof RateLimitError) {
console.error('Rate limit exceeded. Please wait.');
// Implement retry with exponential backoff
} else if (error instanceof NetworkError) {
console.error('Network error:', error.message);
// Show offline UI or retry
} else {
console.error('Unexpected error:', error);
}
}🏗️ Architecture
The SDK follows a resource-based OOP architecture with clear separation of concerns:
DataCanvas SDK
├── DataCanvas (Main Client)
│ ├── devices (DevicesResource)
│ └── data (DataResource)
├── HttpClient (HTTP Communication)
├── Exceptions (Error Hierarchy)
├── Constants (Enums & Defaults)
└── Types (TypeScript Definitions)📄 TypeScript Support
The SDK is written in TypeScript and provides comprehensive type definitions.
import type {
SDKConfig,
DeviceResponse,
Device,
DataResponse,
DataPoint,
GetDataParams,
} from '@datacanvas/sdk';
// All types are exported and available for use
const config: SDKConfig = {
access_key_client: 'key',
access_key_secret: 'secret',
projectId: 123,
baseUrl: 'https://api.<something>.<something>', // Optional
};🤝 Contributing
Contributions are welcome! Please follow these guidelines:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'feat: add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Development Setup
# Clone repository
git clone https://github.com/Datacanvas-IoT/Datacanvas-NPM
cd Datacanvas-NPM
# Install dependencies
npm install
# Build project
npm run build
# Run tests
npm test📝 License
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
🔗 Resources
💬 Support
For questions, issues, or feature requests:
- 📧 Email: [email protected], [email protected], [email protected]
- 🐛 Issues: GitHub Issues
- 💬 Discussions: GitHub Discussions
