@safercity/sdk-core
v0.0.1
Published
Core utilities for SaferCity SDK - fetch abstraction, streaming, and authentication
Downloads
76
Maintainers
Readme
@safercity/sdk-core
Core utilities for SaferCity SDK including fetch abstraction, streaming support, and authentication helpers.
Note: Most users should use
@safercity/sdkinstead. This package contains low-level utilities used internally.
Installation
npm install @safercity/sdk-coreFeatures
- Type definitions - Common types for API requests/responses
- Authentication utilities - Token management, JWT parsing
- Streaming/SSE support - Cross-platform Server-Sent Events
- Base HTTP client - Fetch wrapper with timeout and error handling
Usage
Stream Adapters
import {
WebStreamAdapter,
FetchStreamAdapter,
createStreamAdapter
} from '@safercity/sdk-core';
// Auto-detect best adapter for environment
const adapter = createStreamAdapter();
// Or use specific adapter
const webAdapter = new WebStreamAdapter(); // Browser with EventSource
const fetchAdapter = new FetchStreamAdapter(fetch); // Node.js / React Native
// Stream events
const stream = adapter.createEventSource('https://api.example.com/stream', {
headers: { Authorization: 'Bearer token' },
});
for await (const event of stream) {
console.log(event.data);
}Authentication Helpers
import {
createAuthHeader,
parseJwtPayload,
getJwtExpiration,
isTokenExpired,
} from '@safercity/sdk-core';
// Create auth header
const header = createAuthHeader('my-token'); // "Bearer my-token"
// Parse JWT (without verification)
const payload = parseJwtPayload(token);
console.log(payload?.sub); // User ID
// Check expiration
const expiresAt = getJwtExpiration(token);
if (isTokenExpired(expiresAt)) {
// Token expired, refresh it
}Base Client
import { BaseClient } from '@safercity/sdk-core';
const client = new BaseClient({
baseUrl: 'https://api.example.com',
token: 'my-token',
timeout: 30000,
});
// Make requests
const response = await client.get('/users');
const created = await client.post('/users', { name: 'John' });Error Handling
import { SaferCityApiError } from '@safercity/sdk-core';
try {
await client.get('/not-found');
} catch (error) {
if (error instanceof SaferCityApiError) {
console.log(error.error); // "not_found"
console.log(error.message); // "Resource not found"
console.log(error.status); // 404
}
}Types
SaferCityConfig
interface SaferCityConfig {
baseUrl: string;
token?: string;
tenantId?: string;
fetch?: typeof fetch;
timeout?: number;
headers?: Record<string, string>;
}ServerSentEvent
interface ServerSentEvent {
id?: string;
event?: string;
data: string;
retry?: number;
}License
MIT
