gowavey-sdk-web
v1.4.4
Published
A JavaScript/TypeScript SDK for integrating GoWavey functionality into Web and React applications
Readme
GoWavey JS SDK
A lightweight JavaScript/TypeScript SDK for integrating GoWavey functionality into Web and React applications.
Installation
npm install gowavey-sdk-webor
yarn add gowavey-sdk-webUsage
Member Initialization (Recommended)
The SDK now supports automatic member creation and management with deduplication. This is the recommended approach as it eliminates the need to manage member IDs manually.
import { GoWaveySDK } from 'gowavey-sdk-web';
const sdk = new GoWaveySDK({
appKey: 'your-app-key',
endpoint: 'https://api.gowavey.com/v1', // optional, this is the default
timeout: 30000 // optional, request timeout in ms
});
// Initialize the SDK (creates or retrieves member)
const result = await sdk.initialize({
userId: 'user-123', // Optional: for cross-device sync
memberName: 'John Doe', // Optional: display name
metadata: { // Optional: custom metadata
version: '1.0.0',
environment: 'production'
}
});
console.log('Member ID:', result.memberId);
console.log('Is new member:', result.isNewMember);
console.log('Source:', result.source); // 'localStorage' or 'backend'
// After initialization, you can call methods without passing memberId
const response = await sdk.updateActivity('activity-123', 'new-value');
console.log('Activity updated:', response.Payload);
// Get trophies without passing memberId
const trophies = await sdk.getTrophies();
console.log('Trophies:', trophies);
// You can also retrieve the stored member ID
const memberId = sdk.getMemberId();
console.log('Current member ID:', memberId);Basic Usage (Without Initialization)
You can still use the SDK without initialization by passing the member ID to each method call:
import { GoWaveySDK, ValidationError, AuthenticationError } from 'gowavey-sdk-web';
const sdk = new GoWaveySDK({
appKey: 'your-app-key',
endpoint: 'https://api.gowavey.com/v1', // optional, this is the default
timeout: 30000 // optional, request timeout in ms
});
// Update an activity
try {
const response = await sdk.updateActivity('activity-123', 'new-value', 'member-456');
console.log('Activity updated:', response.Payload);
} catch (error) {
if (error instanceof ValidationError) {
console.error('Invalid input:', error.message);
} else if (error instanceof AuthenticationError) {
console.error('Authentication failed:', error.message);
} else {
console.error('Error:', error);
}
}
// Get trophies
const trophies = await sdk.getTrophies('member-456');
console.log('Trophies:', trophies);React Hook
With Member Initialization (Recommended)
import { useGoWavey } from 'gowavey-sdk-web';
import { useEffect, useState } from 'react';
function ActivityComponent() {
const { initialize, updateActivity, getTrophies, getMemberId } = useGoWavey({
appKey: 'your-app-key',
endpoint: 'https://api.gowavey.com/v1' // optional
});
const [memberId, setMemberId] = useState<string | null>(null);
const [isInitialized, setIsInitialized] = useState(false);
useEffect(() => {
// Initialize on component mount
const initSDK = async () => {
try {
const result = await initialize({
userId: 'user-123',
memberName: 'John Doe'
});
setMemberId(result.memberId);
setIsInitialized(true);
console.log('SDK initialized:', result);
} catch (error) {
console.error('Initialization failed:', error);
}
};
initSDK();
}, [initialize]);
const handleActivityUpdate = async () => {
if (!isInitialized) {
console.error('SDK not initialized yet');
return;
}
try {
// No need to pass memberId after initialization
const response = await updateActivity('activity-123', 'new-value');
console.log('Activity updated:', response.Payload);
// Fetch updated trophies
const trophies = await getTrophies();
console.log('Updated trophies:', trophies);
} catch (error) {
console.error('Error updating activity:', error);
}
};
return (
<div>
<p>Member ID: {memberId || 'Not initialized'}</p>
<button onClick={handleActivityUpdate} disabled={!isInitialized}>
Update Activity
</button>
</div>
);
}Without Initialization
import { useGoWavey } from 'gowavey-sdk-web';
function ActivityComponent() {
const { updateActivity, getTrophies } = useGoWavey({
appKey: 'your-app-key',
endpoint: 'https://api.gowavey.com/v1' // optional
});
const handleActivityUpdate = async () => {
try {
const response = await updateActivity('activity-123', 'new-value', 'member-456');
console.log('Activity updated:', response.Payload);
// Fetch updated trophies (per member)
const trophies = await getTrophies('member-456');
console.log('Updated trophies:', trophies);
} catch (error) {
console.error('Error updating activity:', error);
}
};
return (
<div>
<button onClick={handleActivityUpdate}>
Update Activity
</button>
</div>
);
}API Reference
GoWaveySDK
Constructor
constructor(config: GoWaveyConfig): Create a new instance of the SDK
Methods
initialize(options?: MemberInitOptions): Promise<MemberInitResult>: Initialize the SDK by creating or retrieving a member. Checks local storage first, then calls the backend if needed.getMemberId(): string | null: Get the current member ID from memory or local storageupdateActivity(activityId: string, value: string, memberId?: string): Promise<UpdateActivityResponse>: Update an activity for a member. If memberId is not provided, uses the stored member ID from initialization.getTrophies(memberId?: string): Promise<GetTrophiesResponse>: Get trophies for a member. If memberId is not provided, uses the stored member ID from initialization.
useGoWavey Hook
useGoWavey(config: GoWaveyConfig): React hook for using the GoWavey SDK- Returns an object with:
initialize: Function to initialize the SDK and create/retrieve a membergetMemberId: Function to get the current member IDupdateActivity: Function to update an activitygetTrophies: Function to get trophies for a membersdk: The underlying SDK instance
- Returns an object with:
Types
interface GoWaveyConfig {
appKey: string;
endpoint?: string; // Default: 'https://api.gowavey.com/v1'
timeout?: number; // Request timeout in milliseconds
}
interface MemberInitOptions {
userId?: string; // Optional: User ID for cross-device deduplication
memberName?: string; // Optional: Display name for the member
metadata?: Record<string, any>; // Optional: Custom metadata
}
interface MemberInitResult {
memberId: string; // The member ID (created or retrieved)
isNewMember: boolean; // Whether this is a newly created member
source: 'localStorage' | 'backend'; // Where the member ID came from
}
interface UpdateActivityResponse {
Payload: {
Rewards: Reward[];
Count: number;
}
}
interface GetTrophiesResponse {
backgroundColor: string;
countInRow: number;
rewards: Reward[];
}
interface Reward {
name: string;
badgeUrl: string;
animationId: string;
isAchieved: boolean;
}Member Initialization Details
How It Works
The member initialization system prevents duplicate member creation through a hybrid approach:
- Local Storage Check: The SDK first checks browser localStorage for an existing member ID
- Backend Deduplication: If no local member ID exists, it calls the backend API which:
- Checks for existing members by device ID
- Checks for existing members by user ID (if provided)
- Creates a new member only if no match is found
- Returns the member ID and whether it's a new member
- Local Storage: The member ID is stored in localStorage for future use
Device ID Generation
The SDK automatically generates a unique device ID that persists in localStorage:
- Format:
web_{timestamp}_{random} - Used for device-based deduplication
- Survives browser sessions but is cleared when localStorage is cleared
Cross-Device Sync
By providing a userId during initialization, you can:
- Sync the same member across multiple devices
- Maintain member identity when a user logs in on different browsers
- Prevent duplicate members for authenticated users
Storage Keys
The SDK uses the following localStorage keys:
gowavey_member_id: Stores the member IDgowavey_device_id: Stores the device ID
To clear all SDK data:
localStorage.removeItem('gowavey_member_id');
localStorage.removeItem('gowavey_device_id');Error Handling
The SDK provides typed error classes for better error handling:
GoWaveyError: Base error classValidationError: Input validation failedAuthenticationError: API key is invalid or missingNotFoundError: Resource not foundRateLimitError: API rate limit exceededNetworkError: Network connection issuesTimeoutError: Request timeoutServerError: Server-side errors
import { ValidationError, AuthenticationError } from 'gowavey-sdk-web';
try {
await sdk.updateActivity('', 'value', 'member');
} catch (error) {
if (error instanceof ValidationError) {
// Handle validation error
}
}Debug Mode
The SDK includes comprehensive debug logging to help with troubleshooting and development. When enabled, it logs detailed information about SDK operations including initialization, API requests, responses, and errors.
Enabling Debug Mode
Browser (localStorage):
localStorage.setItem('GOWAVEY_DEBUG', 'true');Browser (sessionStorage):
sessionStorage.setItem('GOWAVEY_DEBUG', 'true');Node.js (environment variable):
GOWAVEY_DEBUG=true node your-app.jsDebug Output
When debug mode is enabled, you'll see console logs like:
[GoWavey Debug 2024-01-15T10:30:00.000Z] GoWavey SDK initialized successfully {endpoint: "https://api.gowavey.com/v1", timeout: 30000, appKeyLength: 32}
[GoWavey Debug 2024-01-15T10:30:01.000Z] Updating activity {activityId: "activity-123", value: "new-value", memberId: "member-456"}
[GoWavey Debug 2024-01-15T10:30:01.100Z] Making API request to activity/process {method: "POST", fullUrl: "https://api.gowavey.com/v1/activity/process", timeout: 30000, headers: {...}, body: {...}}
[GoWavey Debug 2024-01-15T10:30:01.250Z] API request successful for activity/process {status: 200, contentType: "application/json", responseSize: 156}
[GoWavey Debug 2024-01-15T10:30:01.251Z] Activity updated successfully {Payload: {Rewards: [...], Count: 1}}Debug Information Includes:
- SDK Initialization: Configuration details (endpoint, timeout, API key length)
- Method Calls: Parameters passed to
updateActivity()andgetTrophies() - API Requests: HTTP method, URL, timeout, headers (with redacted authorization)
- API Responses: Status codes, content types, response sizes
- Errors: Detailed error information for timeouts, network issues, and API failures
Security Note
Debug logs automatically redact sensitive information like API keys in request headers, showing [REDACTED] instead of the actual values.
License
This project is licensed under the MIT License.
