session-handler-client
v1.0.1
Published
A React client library for interacting with the Session Handler Server API. This library provides an easy-to-use interface for managing sessions and session activities.
Readme
Session Handler Client
A React client library for interacting with the Session Handler Server API. This library provides an easy-to-use interface for managing sessions and session activities.
Installation
npm install session-handler-client axiosNote: axios is a peer dependency and must be installed separately.
Usage
import { SessionClient } from 'session-handler-client';
// Initialize the client
const sessionClient = new SessionClient({
baseUrl: 'http://localhost:3000/api',
setLoadingState: (isLoading) => {
// Handle loading state in your UI
console.log('Loading:', isLoading);
},
setDynamicRendererState: (state) => {
// Handle dynamic renderer state changes
console.log('Renderer state updated:', state);
}
});
// Example: Create a new session
async function createSession() {
try {
const response = await sessionClient.addSession();
if (response.success) {
console.log('Session created:', response.data);
return response.data;
}
} catch (error) {
console.error('Error creating session:', error);
}
}
// Example: Initiate a session flow
async function startSessionFlow() {
try {
const response = await sessionClient.initiateSession();
if (response.success) {
console.log('Session initiated:', response.data);
// The DynamicRendererState is automatically updated via the callback
}
} catch (error) {
console.error('Error initiating session:', error);
}
}
// Example: Continue a session flow
async function continueFlow(sessionId) {
try {
const response = await sessionClient.continueSession(sessionId);
if (response.success) {
console.log('Session continued:', response.data);
// The DynamicRendererState is automatically updated via the callback
}
} catch (error) {
console.error('Error continuing session:', error);
}
}API Reference
SessionClient
Main client class for interacting with the Session Handler Server API.
Constructor
new SessionClient({
baseUrl: string; // The base URL of the API
setLoadingState: (isLoading: boolean) => void; // Callback for loading state changes
setDynamicRendererState: (state: DynamicRendererState) => void; // Callback for renderer state changes
})Methods
addSession(): Create a new sessiongetSessionById(sessionId: string): Get a session by IDaddSessionActivity(sessionId: string, activityData: Activity): Add activity to a sessionupdateSessionActivity(sessionId: string, activityId: string, modifications: ActivityModifications): Update an activitydeleteSession(sessionId: string): Delete a sessiondeleteSessionActivity(sessionId: string, activityId: string): Delete an activitygetLastSessionActivity(sessionId: string): Get the last activity in a sessiongetSessionSummary(sessionId: string): Get summary of session activitiesinitiateSession(): Start a new session flowcontinueSession(sessionId: string): Continue an existing session flow
Types
ApiResponse<T>
interface ApiResponse<T> {
success: boolean;
data: T | null;
error?: string;
}Session
Represents a session with activities and other metadata.
Activity
Represents an activity within a session.
ActivityModifications
Represents changes to be applied to an activity.
DynamicRendererState
Represents the state for dynamic rendering of components.
Integration with React
The library provides a DynamicRenderer component that simplifies integration with React applications. This component manages the session state and renders the appropriate UI based on the current session activity.
Here's a real-world example from the test-client project:
import React, { useState } from 'react';
import { DynamicRenderer as DR } from 'session-handler-client';
import './spinner.css';
import ActionComponents from './components/ActionComponents';
// Type assertion to work around React type conflicts
const DynamicRenderer = DR as any;
function App() {
const [loading, setLoading] = useState<boolean>(false);
return (
<div className="App" style={{
maxWidth: '800px',
margin: '0 auto',
padding: '20px',
fontFamily: 'Arial, sans-serif',
position: 'relative'
}}>
{loading && (
<div style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
backgroundColor: 'rgba(255, 255, 255, 0.7)',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
zIndex: 1000,
borderRadius: '5px'
}}>
<div className="spinner"></div>
</div>
)}
<header style={{
background: '#f4f4f4',
padding: '20px',
borderRadius: '5px',
marginBottom: '20px'
}}>
<h1 style={{ margin: '0 0 10px 0', color: '#333' }}>
Session Handler Client Test
</h1>
<p style={{ margin: '0', color: '#666' }}>
Simple test environment for the session-handler-client package
</p>
</header>
<div style={{
marginTop: '30px',
background: '#f9f9f9',
padding: '15px',
borderRadius: '5px',
border: '1px solid #ddd'
}}>
<DynamicRenderer
baseUrl='http://localhost:7777/session'
setLoadingState={(a:boolean) => setLoading(a)}
actionComponents={ActionComponents}
/>
</div>
</div>
);
}Action Components
The DynamicRenderer component takes an actionComponents prop which is a map of action names to React components. Each component receives the session data and can render accordingly.
Here's an example of a generic action component:
import React from 'react';
interface GenericActionProps {
session: any;
sessionId: string;
lastActivity: any;
nextAction?: () => void;
}
const GenericAction: React.FC<GenericActionProps> = ({ session, sessionId, lastActivity }) => {
// Extract the action name from lastActivity
const actionName = lastActivity?.actionName || 'Unknown Action';
return (
<div className="generic-action-component" style={{
maxWidth: '600px',
margin: '20px auto',
padding: '20px',
borderRadius: '8px',
boxShadow: '0 2px 10px rgba(0, 0, 0, 0.1)',
backgroundColor: '#fff'
}}>
<h2 style={{ marginTop: 0, color: '#333' }}>Action: {actionName}</h2>
<p>This is a generic action component for: <strong>{actionName}</strong></p>
<p>Parameters: {JSON.stringify(lastActivity?.actionParam || {})}</p>
</div>
);
};License
ISC
