@mzbg/sdk-core
v0.1.1
Published
Configuration driven core functionality to build the client side SDK / API layer
Downloads
133
Readme
SDK Core
SDK Core provides configuration based SDK generation. Its a flexible and feature-rich API SDK backbone that provides a simple interface for making HTTP requests with built-in support for retry logic, polling, and subscription capabilities.
Installation
npm i sdk-core
Basic Usage
import { api } from 'sdk-core';
// Initialize the API
api.init({
axiosConfig: {
baseURL: 'https://api.example.com',
headers: {
'Content-Type': 'application/json'
}
},
endpoints: [
// Your endpoint configurations
]
});
// Make a request
const userDetails = await api.user.get({
params: {
userId: loginResponse.data.id,
},
});
Making Direct Calls
You can also make direct API calls by passing an object with url and other configs:
// GET request
const response = await api.get({
url: '/users/123',
params: {
fields: 'name,email'
}
});
// POST request
const newUser = await api.post({
url: '/users',
data: {
name: 'John Doe',
email: '[email protected]'
}
});
// PUT request
const updatedUser = await api.put({
url: '/users/123',
data: {
name: 'John Updated'
}
});
// DELETE request
await api.delete({
url: '/users/123'
});
Features
1. Request Interceptors
You can intercept requests and responses:
// Request interceptor
api.interceptRequest(
(config) => {
// Modify request config
return config;
},
(error) => {
// Handle request error
return Promise.reject(error);
}
);
// Response interceptor
api.interceptResponse(
(response) => {
// Handle response
return response;
},
(error) => {
// Handle response error
return Promise.reject(error);
}
);
2. Polling and Subscriptions
The SDK supports automatic polling and subscription to endpoints:
subscribe method accepts 3 arguments:
- (Required) Endpoint method
- (Required) Callback function (to be called when data is received / error occurs)
- (Optional) Request configuration provider (to be called before each request)
// Subscribe to an endpoint
const callback = (data) => {
console.log('Received updated data:', data);
};
const requestConfigProvider = () => {
const requestConfig = {
params: {
id: 1
}
};
return requestConfig;
}
api.subscribe(api.users.get, callback, requestConfigProvider);
// Unsubscribe from an endpoint
api.unsubscribe(api.users.get, callback);
3. Api response caching
SDK Core provides built-in caching capabilities:
// Configure cache settings
api.init({
cache: {
enabled: true,
ttl: 60000, // Cache TTL in milliseconds
storageType: 'memory', // 'memory' or 'localStorage'
maxSize: 100 // Maximum number of cached items
}
});
// Make a cached request
const cachedData = await api.users.get({
cache: {
key: 'users-list',
ttl: 30000, // Override default TTL
condition: (response) => response.status === 200
}
});
// Clear specific cache
api.cache.delete('users-list');
// Clear all cache
api.cache.clear();
// Get cache stats
const stats = api.cache.getStats();
You can also implement custom cache adapters:
class CustomCache {
get(key) { /* ... */ }
set(key, value, ttl) { /* ... */ }
delete(key) { /* ... */ }
clear() { /* ... */ }
getStats() { /* ... */ }
}
api.init({
cache: {
adapter: new CustomCache()
}
});
4. Configuration driven
Basic Example
This example shows a simple configuration with a single endpoint and method:
api.init({
endpoints: [
{
name: 'users',
url: '/users',
methods: [
{
method: 'get'
}
]
}
]
});
Nested Endpoints Example
This example demonstrates how to configure nested endpoints, useful for hierarchical APIs:
api.init({
endpoints: [
{
name: 'organization',
url: '/org',
methods: [
{
method: 'get'
}
],
endpoints: [
{
name: 'teams',
url: '/teams',
methods: [
{
method: 'get'
}
],
endpoints: [
{
name: 'members',
url: '/members',
methods: [
{
method: 'get'
}
]
}
]
}
]
}
]
});
// Can be accessed as:
await api.organization.teams.members.get({
params: {
orgId: 123,
teamId: 456,
memberId: 789
}
});
Endpoint Configuration
Each endpoint can be configured with:
name
: Endpoint identifierurl
: Endpoint URLmethods
: Array of method configurationsendpoints
: Nested endpoints
Method Configuration
Methods can be configured with:
method
: HTTP methodurl
: Method-specific URLretry
: Method-specific retry configurationpolling
: Polling configuration
Error Handling
The SDK throws errors for:
- Uninitialized API
- Invalid parameter types
- Missing required parameters
- Invalid endpoint configurations
- Failed requests
TODO
There are a few features that are planned for future releases:
- Add support to validate request params and payload using ajv schema
- Add support for configuring and seding requests to multiple servers
- Add request chaining support
- Add request pipeline support
- Add request dependency resolution
- Add GraphQL support
- Implement WebSocket support for real-time updates
- Implement automatic request batching
- Add implementation to handle authentication
- Enable request rate limiting
- Add response data transformation helpers
- Add OpenAPI/Swagger schema generation and validation
- Add caching layer support with offline capability
- Add request throttling and concurrent request handling
- Add request mocking support for testing
- Add logging and analytics capabilities
- Implement API analytics and performance monitoring
- Add support for distributed tracing
- Add CORS handling and configuration
- Add support for file uploads and progress tracking
- Implement custom response serializers/deserializers
- Add support for circuit breaker pattern
- Implement request prioritization and queuing
- Add API discovery and documentation generation
- Add support for response streaming
- Add response schema validation
- Add support for middleware and plugin architecture
- Add support for custom header management
TypeScript Support
The SDK is written in TypeScript and provides full type definitions for all features.
License
This package is licensed under MIT or Apache-2.0 license