@well-prado/blok-front-sdk-core
v1.0.2
Published
Core utilities and types for Blok Framework frontend integration with workflow communication
Downloads
8
Maintainers
Readme
@well-prado/blok-front-sdk-core
Core utilities and types for Blok Framework frontend integration with workflow communication.
Overview
The @well-prado/blok-front-sdk-core package provides the foundational layer for all Blok Framework frontend packages. It includes core utilities, HTTP client, type definitions, and validation helpers that enable seamless communication between frontend applications and Blok Framework backends.
Features
- 🌐 HTTP Client - Pre-configured client for Blok workflow communication
- 🔒 Type Safety - Complete TypeScript definitions for all workflow interactions
- ✅ Validation - Built-in request/response validation
- 🚀 Performance - Optimized for minimal bundle size
- 🔧 Extensible - Easy to extend with custom configurations
Installation
npm install @well-prado/blok-front-sdk-coreQuick Start
Basic Client Usage
import { BlokClient } from "@well-prado/blok-front-sdk-core";
// Initialize the client
const client = new BlokClient({
baseURL: "http://localhost:4000",
timeout: 10000,
});
// Execute a workflow
const result = await client.executeWorkflow("user-login", {
email: "[email protected]",
password: "securepassword",
});
console.log(result.data); // Workflow responseWith Custom Configuration
import { BlokClient, BlokClientConfig } from "@well-prado/blok-front-sdk-core";
const config: BlokClientConfig = {
baseURL: process.env.REACT_APP_API_URL || "http://localhost:4000",
timeout: 15000,
headers: {
"Custom-Header": "value",
},
withCredentials: true,
};
const client = new BlokClient(config);API Reference
BlokClient
The main client class for communicating with Blok Framework backends.
Constructor
new BlokClient(config: BlokClientConfig)Configuration Options
| Option | Type | Default | Description |
| ----------------- | ------------------------ | ------------------------- | -------------------------------- |
| baseURL | string | 'http://localhost:4000' | Base URL for the Blok backend |
| timeout | number | 10000 | Request timeout in milliseconds |
| headers | Record<string, string> | {} | Default headers for all requests |
| withCredentials | boolean | true | Include cookies in requests |
Methods
executeWorkflow<T>(workflowName: string, data?: any): Promise<BlokResponse<T>>
Execute a Blok workflow with optional input data.
// Simple workflow execution
const response = await client.executeWorkflow("get-user-profile");
// With input data
const response = await client.executeWorkflow("update-profile", {
name: "John Doe",
email: "[email protected]",
});get<T>(path: string, params?: any): Promise<BlokResponse<T>>
Make a GET request to a specific path.
const response = await client.get("/api/users", { page: 1, limit: 10 });post<T>(path: string, data?: any): Promise<BlokResponse<T>>
Make a POST request with data.
const response = await client.post("/api/users", {
name: "Jane Doe",
email: "[email protected]",
});Types
BlokResponse
Standard response format for all Blok operations.
interface BlokResponse<T = any> {
data: T;
success: boolean;
message?: string;
error?: BlokError;
metadata?: {
timestamp: string;
requestId: string;
executionTime: number;
};
}BlokError
Error information for failed operations.
interface BlokError {
code: string;
message: string;
details?: any;
stack?: string;
}BlokClientConfig
Configuration options for the BlokClient.
interface BlokClientConfig {
baseURL?: string;
timeout?: number;
headers?: Record<string, string>;
withCredentials?: boolean;
}Validation
The package includes built-in validation for common data types:
import {
validateEmail,
validateRequired,
} from "@well-prado/blok-front-sdk-core";
// Email validation
const isValidEmail = validateEmail("[email protected]"); // true
// Required field validation
const isValid = validateRequired("some value"); // true
const isInvalid = validateRequired(""); // falseAvailable Validators
validateEmail(email: string): boolean- Validates email formatvalidateRequired(value: any): boolean- Checks if value is not emptyvalidateMinLength(value: string, min: number): boolean- Minimum length validationvalidateMaxLength(value: string, max: number): boolean- Maximum length validation
Error Handling
The SDK provides comprehensive error handling:
try {
const result = await client.executeWorkflow("some-workflow");
} catch (error) {
if (error instanceof BlokError) {
console.error("Blok Error:", error.code, error.message);
} else {
console.error("Network Error:", error.message);
}
}Advanced Usage
Custom Headers
// Set default headers for all requests
const client = new BlokClient({
baseURL: "http://localhost:4000",
headers: {
Authorization: "Bearer token",
"X-Custom-Header": "value",
},
});
// Override headers for specific requests
const response = await client.executeWorkflow("protected-workflow", data, {
headers: {
"X-Request-ID": "unique-id",
},
});Request Interceptors
// Add request interceptor
client.addRequestInterceptor((config) => {
config.headers["X-Timestamp"] = Date.now().toString();
return config;
});
// Add response interceptor
client.addResponseInterceptor((response) => {
console.log("Response received:", response.metadata?.requestId);
return response;
});Integration with React
While this package works with any JavaScript framework, it's designed to work seamlessly with React:
import { BlokClient } from "@well-prado/blok-front-sdk-core";
import { useEffect, useState } from "react";
function UserProfile() {
const [user, setUser] = useState(null);
const client = new BlokClient();
useEffect(() => {
const loadUser = async () => {
try {
const response = await client.executeWorkflow("get-user-profile");
setUser(response.data);
} catch (error) {
console.error("Failed to load user:", error);
}
};
loadUser();
}, []);
return <div>{user ? <h1>Hello, {user.name}</h1> : <p>Loading...</p>}</div>;
}TypeScript Support
This package is built with TypeScript and provides full type safety:
// Define your workflow types
interface LoginRequest {
email: string;
password: string;
}
interface LoginResponse {
user: {
id: string;
name: string;
email: string;
};
token: string;
}
// Use with full type safety
const response = await client.executeWorkflow<LoginResponse>("user-login", {
email: "[email protected]",
password: "password",
} as LoginRequest);
// TypeScript knows the response structure
console.log(response.data.user.name); // ✅ Type safe
console.log(response.data.invalid); // ❌ TypeScript errorEnvironment Configuration
Configure the SDK for different environments:
// Development
const devClient = new BlokClient({
baseURL: "http://localhost:4000",
timeout: 30000, // Longer timeout for debugging
});
// Production
const prodClient = new BlokClient({
baseURL: "https://api.myapp.com",
timeout: 10000,
headers: {
"X-Environment": "production",
},
});
// Use environment variables
const client = new BlokClient({
baseURL: process.env.REACT_APP_API_URL,
timeout: parseInt(process.env.REACT_APP_API_TIMEOUT || "10000"),
});Testing
The package includes utilities for testing:
import { BlokClient, createMockClient } from "@well-prado/blok-front-sdk-core";
// Create a mock client for testing
const mockClient = createMockClient();
// Mock workflow responses
mockClient.mockWorkflow("user-login", {
data: { user: { id: "1", name: "Test User" } },
success: true,
});
// Use in tests
const response = await mockClient.executeWorkflow("user-login");
expect(response.data.user.name).toBe("Test User");Performance Tips
- Reuse Client Instances: Create one client instance and reuse it throughout your application.
// ✅ Good - Create once
const client = new BlokClient(config);
// ❌ Avoid - Creating multiple instances
function someFunction() {
const client = new BlokClient(config); // Don't do this
}- Use Request Cancellation: Cancel requests when components unmount.
useEffect(() => {
const controller = new AbortController();
client.executeWorkflow(
"load-data",
{},
{
signal: controller.signal,
}
);
return () => controller.abort();
}, []);Troubleshooting
Common Issues
CORS Errors: Ensure your backend allows requests from your frontend domain.
Timeout Issues: Increase timeout for slow workflows:
const client = new BlokClient({ timeout: 30000 });Authentication Issues: Make sure
withCredentials: trueis set for cookie-based auth.
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
Related Packages
@well-prado/blok-react-sdk- React hooks and components@well-prado/blok-codegen- TypeScript code generation@well-prado/blok-admin-dashboard- Complete backend solution@well-prado/blok-cli- CLI for project management
