@letsparky/api-v2-client
Version:
TypeScript client for the LetsParky API V2
311 lines (310 loc) • 12.7 kB
TypeScript
/// <reference types="node" />
/// <reference types="node" />
import { ApiClient } from './client';
import { DeviceLog, DeviceLogFilters, DeviceLogListResponse, DeviceAnalytics, DeviceAnalyticsParams, DeviceLogCount, DeviceLogCountParams, DeviceLogCleanupParams, DeviceLogCleanupResponse, ApiResponse, DeviceUUID } from './types';
/**
* Device logs management client for the LetsParky API.
*
* This class provides comprehensive device logs functionality including:
* - Retrieving device logs with advanced filtering
* - Getting analytics summaries for devices
* - Fetching latest logs for specific devices
* - Getting hourly statistics for devices
* - Counting logs with time range filtering
* - Administrative cleanup operations
*
* All timestamp parameters support both ISO 8601 date strings and Unix timestamps
* in milliseconds for maximum flexibility.
*
* @example
* ```typescript
* const client = new ApiClient({ apiKey: 'your-api-key' });
* const deviceLogs = new DeviceLogs(client);
*
* // Get logs for a specific device
* const logs = await deviceLogs.list({ device_id: 'device-123' });
*
* // Get analytics for a device using Unix timestamps
* const analytics = await deviceLogs.getAnalytics('device-123', {
* start_time: Date.now() - 30 * 24 * 60 * 60 * 1000, // 30 days ago
* end_time: Date.now()
* });
*
* // Get hourly stats for a device
* const hourlyStats = await deviceLogs.getHourlyStats({
* device_id: 'device-123',
* start_time: Date.now() - 7 * 24 * 60 * 60 * 1000, // 7 days ago
* limit: 168 // 7 days * 24 hours
* });
*
* // Get latest log for a device
* const latestLog = await deviceLogs.getLatest('device-123');
* ```
*
* @since 1.0.0
*/
export declare class DeviceLogs {
private client;
/**
* Creates a new DeviceLogs instance.
*
* @param client - The ApiClient instance to use for API requests
*
* @since 1.0.0
*/
constructor(client: ApiClient);
/**
* Converts a timestamp (Unix milliseconds or ISO string) to ISO string format for API requests
*
* @private
* @param timestamp - The timestamp to convert
* @returns ISO string representation
*/
private timestampToISOString;
/**
* Validates and converts a timestamp for API usage
*
* @private
* @param timestamp - The timestamp to validate and convert
* @param fieldName - The field name for error messages
* @returns ISO string representation
*/
private validateAndConvertTimestamp;
/**
* Retrieves device logs with optional filtering.
*
* This method provides comprehensive filtering capabilities for device logs
* including device-specific filtering, status filtering, time range filtering,
* and pagination using offset-based pagination.
*
* @param filters - Optional filter parameters for device logs
* @param filters.limit - Maximum number of logs to return (1-1000, default: 100)
* @param filters.page - Page number (1-100, default: 1)
* @param filters.device_id - Filter by specific device ID
* @param filters.device_ids - Filter by multiple device IDs
* @param filters.status - Filter by device status (string or array of strings)
* @param filters.blocked - Filter by blocked status
* @param filters.has_alarm - Filter by alarm presence
* @param filters.start_time - Filter logs from this timestamp (ISO string or Unix timestamp)
* @param filters.end_time - Filter logs until this timestamp (ISO string or Unix timestamp)
* @returns Promise resolving to device logs with pagination metadata
*
* @throws {ValidationError} When filter parameters are invalid
* @throws {AuthenticationError} When authentication is required or fails
* @throws {ApiError} When the API returns an error response
* @throws {NetworkError} When the request fails due to network issues
*
* @example
* ```typescript
* const deviceLogs = new DeviceLogs(client);
*
* // Get recent logs for a specific device
* const response = await deviceLogs.list({
* device_id: 'device-123',
* limit: 50,
* offset: 0
* });
*
* // Get logs with alarms for multiple devices using timestamps
* const alarmsResponse = await deviceLogs.list({
* device_ids: ['device-123', 'device-456'],
* has_alarm: true,
* start_time: Date.now() - 7 * 24 * 60 * 60 * 1000, // 7 days ago
* limit: 100
* });
*
* console.log(`Found ${response.data.pagination.total} logs`);
* ```
*
* @since 1.0.0
*/
list(filters?: DeviceLogFilters): Promise<ApiResponse<DeviceLogListResponse>>;
/**
* Retrieves analytics summary for a specific device.
*
* This method provides comprehensive analytics data for a device including
* log counts, status distributions, alarm statistics, and activity summaries
* within the specified time range.
*
* @param deviceId - The unique identifier of the device
* @param params - Optional parameters for analytics filtering
* @param params.start_time - Analytics start time (ISO 8601 format or Unix timestamp)
* @param params.end_time - Analytics end time (ISO 8601 format or Unix timestamp)
* @returns Promise resolving to device analytics data
*
* @throws {ValidationError} When device ID or parameters are invalid
* @throws {AuthenticationError} When authentication is required or fails
* @throws {ApiError} When the device is not found or no analytics data is available
* @throws {NetworkError} When the request fails due to network issues
*
* @example
* ```typescript
* const deviceLogs = new DeviceLogs(client);
*
* // Get analytics for the last 30 days using Unix timestamps
* const analytics = await deviceLogs.getAnalytics('device-123', {
* start_time: Date.now() - 30 * 24 * 60 * 60 * 1000,
* end_time: Date.now()
* });
*
* // Or using ISO strings
* const analyticsISO = await deviceLogs.getAnalytics('device-123', {
* start_time: '2024-01-01T00:00:00Z',
* end_time: '2024-01-31T23:59:59Z'
* });
*
* console.log(`Total logs: ${analytics.data.total_logs}`);
* console.log(`Alarms: ${analytics.data.alarm_count}`);
* console.log(`Status distribution:`, analytics.data.status_distribution);
* ```
*
* @since 1.0.0
*/
getAnalytics(deviceId: DeviceUUID, params?: DeviceAnalyticsParams): Promise<ApiResponse<DeviceAnalytics>>;
/**
* Retrieves the latest log entry for a specific device.
*
* This method fetches the most recent log entry for the specified device,
* which is useful for getting current device status and latest activity.
*
* @param deviceId - The unique identifier of the device
* @returns Promise resolving to the latest device log entry
*
* @throws {ValidationError} When the device ID is invalid
* @throws {AuthenticationError} When authentication is required or fails
* @throws {ApiError} When the device is not found or no logs exist
* @throws {NetworkError} When the request fails due to network issues
*
* @example
* ```typescript
* const deviceLogs = new DeviceLogs(client);
*
* try {
* const latestLog = await deviceLogs.getLatest('device-123');
* console.log(`Latest activity: ${new Date(latestLog.data.logged_at)}`);
* console.log(`Status: ${latestLog.data.status}`);
* console.log(`Battery: ${latestLog.data.battery}%`);
* console.log(`Has alarm: ${latestLog.data.alarm_status ? 'Yes' : 'No'}`);
* } catch (error) {
* if (error instanceof ApiError && error.status === 404) {
* console.log('No logs found for this device');
* }
* }
* ```
*
* @since 1.0.0
*/
getLatest(deviceId: DeviceUUID): Promise<ApiResponse<DeviceLog>>;
/**
* Retrieves the count of logs for a specific device.
*
* This method returns the total number of log entries for a device
* within the specified time range. Useful for monitoring device activity
* levels and data volume estimation.
*
* @param deviceId - The unique identifier of the device
* @param params - Optional parameters for count filtering
* @param params.start_time - Count logs from this timestamp (ISO string or Unix timestamp)
* @param params.end_time - Count logs until this timestamp (ISO string or Unix timestamp)
* @returns Promise resolving to device log count information
*
* @throws {ValidationError} When device ID or parameters are invalid
* @throws {AuthenticationError} When authentication is required or fails
* @throws {ApiError} When the device is not found
* @throws {NetworkError} When the request fails due to network issues
*
* @example
* ```typescript
* const deviceLogs = new DeviceLogs(client);
*
* // Get total log count for a device
* const totalCount = await deviceLogs.getCount('device-123');
* console.log(`Total logs: ${totalCount.data.count}`);
*
* // Get log count for the last week using Unix timestamp
* const weeklyCount = await deviceLogs.getCount('device-123', {
* start_time: Date.now() - 7 * 24 * 60 * 60 * 1000,
* end_time: Date.now()
* });
* console.log(`Logs this week: ${weeklyCount.data.count}`);
* ```
*
* @since 1.0.0
*/
getCount(deviceId: DeviceUUID, params?: DeviceLogCountParams): Promise<ApiResponse<DeviceLogCount>>;
/**
* Performs cleanup of old device logs (admin only).
*
* This method deletes device logs older than the specified timestamp.
* This is an administrative operation that requires appropriate permissions
* and should be used carefully for data retention management.
*
* @param params - Cleanup parameters
* @param params.older_than - Delete logs older than this timestamp (ISO 8601 format or Unix timestamp)
* @returns Promise resolving to cleanup operation results
*
* @throws {ValidationError} When parameters are invalid or missing
* @throws {AuthenticationError} When authentication is required or fails
* @throws {ApiError} When insufficient permissions or operation fails
* @throws {NetworkError} When the request fails due to network issues
*
* @example
* ```typescript
* const deviceLogs = new DeviceLogs(client);
*
* // Clean up logs older than 90 days using Unix timestamp
* const ninetyDaysAgo = Date.now() - 90 * 24 * 60 * 60 * 1000;
*
* try {
* const result = await deviceLogs.cleanup({
* older_than: ninetyDaysAgo
* });
*
* console.log(`Deleted ${result.data.deleted_count} log entries`);
* console.log(`Cutoff date: ${new Date(result.data.cutoff_date)}`);
* } catch (error) {
* if (error instanceof ApiError && error.status === 403) {
* console.error('Insufficient permissions for cleanup operation');
* }
* }
* ```
*
* @since 1.0.0
*/
cleanup(params: DeviceLogCleanupParams): Promise<ApiResponse<DeviceLogCleanupResponse>>;
/**
* Validates that a string is a valid ISO 8601 date-time format.
*
* @private
* @param dateTimeString - The date-time string to validate
* @param fieldName - The name of the field being validated (for error messages)
* @throws {ValidationError} When the date-time string is invalid
*/
private validateDateTimeString;
/**
* Downloads device logs as an Excel (.xlsx) file.
*
* In browser environments this method automatically triggers a file download
* dialog using a temporary link element. In Node.js it returns the file
* contents as a Buffer which can be written to disk manually.
*
* The available query parameters are the same as for {@link list}, with an
* increased limit (up to 1,000,000) to allow exporting large datasets.
*
* @param filters Optional filter parameters for the export
* @param filters.limit Maximum number of logs to include (1–1,000,000)
*
* @example
* ```typescript
* // In a browser
* await deviceLogs.download({ device_id: 'device-123', limit: 5000 });
*
* // In Node.js
* const buffer = await deviceLogs.download({ limit: 10000 });
* require('fs').writeFileSync('device_logs.xlsx', buffer);
* ```
*/
download(filters?: DeviceLogFilters & {
limit?: number;
}): Promise<void | Buffer>;
}