Skip to main content

JavaScript/TypeScript SDK

The Unizo JavaScript SDK provides a convenient way to interact with the Unizo API from client-side and server-side JavaScript applications. It supports both JavaScript and TypeScript with full type definitions.

Installation

NPM

npm install @unizo/sdk

Yarn

yarn add @unizo/sdk

CDN (Browser)

<script src="https://unpkg.com/@unizo/sdk@latest/dist/unizo.min.js"></script>

Basic Setup

Node.js/TypeScript

import { UnizoClient } from '@unizo/sdk';

const unizo = new UnizoClient({
apiKey: 'your-api-key',
environment: 'production', // or 'sandbox'
});

CommonJS

const { UnizoClient } = require('@unizo/sdk');

const unizo = new UnizoClient({
apiKey: process.env.UNIZO_API_KEY,
environment: 'production',
});

Browser

<script>
const unizo = new UnizoSDK.UnizoClient({
apiKey: 'your-public-api-key',
environment: 'production'
});
</script>

Configuration Options

const unizo = new UnizoClient({
apiKey: 'your-api-key',
environment: 'production', // 'production' | 'sandbox'
timeout: 10000, // Request timeout in milliseconds
retryConfig: {
attempts: 3,
delay: 1000,
},
baseURL: 'https://api.unizo.com', // Custom base URL
userAgent: 'MyApp/1.0.0', // Custom user agent
});

Authentication

API Key Authentication

// Set API key during initialization
const unizo = new UnizoClient({
apiKey: 'your-api-key'
});

// Or set it later
unizo.setApiKey('your-api-key');

Bearer Token Authentication

// For user-specific operations
const unizo = new UnizoClient({
bearerToken: 'user-access-token'
});

// Or set it dynamically
unizo.setBearerToken('user-access-token');

Usage Examples

Identity Management

// Get user identity
try {
const identity = await unizo.identity.get();
console.log('User identity:', identity);
} catch (error) {
console.error('Failed to get identity:', error.message);
}

// Update user profile
const updatedProfile = await unizo.identity.update({
name: 'John Doe',
email: 'john@example.com',
metadata: {
department: 'Engineering'
}
});

Source Code Management

// List repositories
const repositories = await unizo.sourceCode.repositories.list({
page: 1,
limit: 50,
provider: 'github'
});

// Get repository details
const repo = await unizo.sourceCode.repositories.get('repo-id');

// Create a webhook
const webhook = await unizo.sourceCode.webhooks.create({
repositoryId: 'repo-id',
url: 'https://your-app.com/webhooks/source-code',
events: ['push', 'pull_request']
});

Ticketing System

// Create a ticket
const ticket = await unizo.ticketing.tickets.create({
title: 'Bug Report: Login Issues',
description: 'Users are experiencing login failures',
priority: 'high',
assignee: 'user-id',
tags: ['bug', 'login', 'urgent']
});

// List tickets with filtering
const tickets = await unizo.ticketing.tickets.list({
status: 'open',
priority: 'high',
assignee: 'current-user',
page: 1,
limit: 25
});

// Update ticket status
const updatedTicket = await unizo.ticketing.tickets.update('ticket-id', {
status: 'in-progress',
comments: [{
text: 'Working on this issue now',
author: 'developer-id'
}]
});

Communications

// Send email
const emailResult = await unizo.communications.email.send({
to: ['user@example.com'],
subject: 'Welcome to Unizo',
template: 'welcome-template',
variables: {
userName: 'John Doe',
activationLink: 'https://app.unizo.com/activate/token'
}
});

// Send SMS
const smsResult = await unizo.communications.sms.send({
to: '+1234567890',
message: 'Your verification code is: 123456'
});

Incident Management

// Create incident
const incident = await unizo.incidents.create({
title: 'API Service Degradation',
description: 'Response times increased by 200%',
severity: 'major',
status: 'investigating',
services: ['api-gateway', 'database']
});

// List active incidents
const activeIncidents = await unizo.incidents.list({
status: 'open',
severity: ['critical', 'major']
});

// Update incident
const updatedIncident = await unizo.incidents.update('incident-id', {
status: 'resolved',
resolution: 'Scaled up database instances'
});

Error Handling

Basic Error Handling

try {
const result = await unizo.identity.get();
} catch (error) {
if (error instanceof UnizoError) {
console.error(`Unizo API Error: ${error.message}`);
console.error(`Status Code: ${error.statusCode}`);
console.error(`Error Code: ${error.code}`);
} else {
console.error('Unexpected error:', error);
}
}

Advanced Error Handling

import { UnizoError, ValidationError, AuthenticationError, RateLimitError } from '@unizo/sdk';

try {
const result = await unizo.ticketing.tickets.create(ticketData);
} catch (error) {
switch (error.constructor) {
case ValidationError:
console.error('Validation failed:', error.details);
break;
case AuthenticationError:
console.error('Authentication failed:', error.message);
// Redirect to login
break;
case RateLimitError:
console.error('Rate limit exceeded, retry after:', error.retryAfter);
// Implement retry logic
break;
default:
console.error('Unknown error:', error);
}
}

Retry Logic

async function withRetry(operation, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await operation();
} catch (error) {
if (error instanceof RateLimitError && attempt < maxRetries) {
await new Promise(resolve => setTimeout(resolve, error.retryAfter * 1000));
continue;
}
throw error;
}
}
}

// Usage
const result = await withRetry(() => unizo.identity.get());

Webhook Handling

import express from 'express';
import { validateWebhookSignature } from '@unizo/sdk';

const app = express();

app.post('/webhooks/unizo', express.raw({type: 'application/json'}), (req, res) => {
const signature = req.headers['x-unizo-signature'];
const payload = req.body;

if (!validateWebhookSignature(payload, signature, process.env.WEBHOOK_SECRET)) {
return res.status(401).send('Invalid signature');
}

const event = JSON.parse(payload);

switch (event.type) {
case 'ticket.created':
console.log('New ticket created:', event.data);
break;
case 'incident.updated':
console.log('Incident updated:', event.data);
break;
default:
console.log('Unknown event type:', event.type);
}

res.status(200).send('OK');
});

TypeScript Support

The SDK includes comprehensive TypeScript definitions:

import { UnizoClient, Ticket, TicketStatus, CreateTicketRequest } from '@unizo/sdk';

const unizo = new UnizoClient({ apiKey: 'your-api-key' });

// Type-safe ticket creation
const ticketData: CreateTicketRequest = {
title: 'Bug Report',
description: 'Detailed description',
priority: 'high', // TypeScript will validate this
tags: ['bug', 'frontend']
};

const ticket: Ticket = await unizo.ticketing.tickets.create(ticketData);

// Type-safe status updates
const status: TicketStatus = 'in-progress';
await unizo.ticketing.tickets.update(ticket.id, { status });

React Hook (Optional)

import { useUnizo } from '@unizo/react-hooks';

function TicketList() {
const { data: tickets, loading, error } = useUnizo(() =>
unizo.ticketing.tickets.list({ status: 'open' })
);

if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;

return (
<ul>
{tickets?.map(ticket => (
<li key={ticket.id}>{ticket.title}</li>
))}
</ul>
);
}

Performance Optimization

Request Caching

const unizo = new UnizoClient({
apiKey: 'your-api-key',
cache: {
enabled: true,
ttl: 300000, // 5 minutes
maxSize: 100 // Max cached responses
}
});

Batch Operations

// Batch multiple ticket creations
const tickets = await unizo.ticketing.tickets.createBatch([
{ title: 'Issue 1', description: 'First issue' },
{ title: 'Issue 2', description: 'Second issue' },
{ title: 'Issue 3', description: 'Third issue' }
]);

Testing

Mocking in Tests

import { UnizoClient } from '@unizo/sdk';
import { jest } from '@jest/globals';

// Mock the entire SDK
jest.mock('@unizo/sdk');
const MockedUnizoClient = UnizoClient as jest.MockedClass<typeof UnizoClient>;

describe('My App', () => {
beforeEach(() => {
MockedUnizoClient.mockClear();
});

test('should create ticket', async () => {
const mockCreate = jest.fn().mockResolvedValue({ id: 'ticket-123' });
MockedUnizoClient.prototype.ticketing = {
tickets: { create: mockCreate }
};

// Your test code here
});
});

Browser Compatibility

The SDK supports all modern browsers:

  • Chrome 60+
  • Firefox 60+
  • Safari 12+
  • Edge 79+

For older browsers, you may need polyfills for:

  • fetch() (or use axios adapter)
  • Promise
  • Object.assign

Resources

Support