@ditype/dios-client-js
v0.0.2
Published
DIOS Client Library for JavaScript/TypeScript
Keywords
Readme
DIOS Client JS
A TypeScript/JavaScript client library for DIOS services, including Lock Service and Mail Gateway.
Installation
npm install @ditype/dios-client-jsThe package provides both CommonJS and ES modules builds.
Requirements
- Node.js 14 or later
- Browsers with ES2020 support
Usage
Lock Service Client
The DIOS Lock Service Client provides a way to synchronize operations across distributed systems using a lock mechanism.
Creating a Client
import { DiosLockServiceClient } from '@ditype/dios-client-js';
// Create client instance
const client = new DiosLockServiceClient(
'https://your-lock-service-url',
'your-jwt-token',
{
retryCount: 3, // How many times to retry failed requests
retryDelay: 200, // Base delay between retries in ms
contentionRetryCount: 5, // Retries for lock contention
contentionRetryDelay: 100, // Delay between contention retries
timeout: 5000, // Request timeout in ms
maxBatchSize: 10, // Max operations in batch requests
setTrustAll: true, // For self-signed certificates
setVerifyHost: false // Disable hostname verification
}
);Using the withLock Method
The withLock method is the recommended way to perform operations with lock protection:
// Execute code with automatic lock acquisition and release
const result = await client.withLock(
'resource-key', // Resource to lock
'my-client-id', // Client identifier
'PT30S', // Lock duration (ISO 8601 format)
async () => {
// Your protected operations here
const data = await fetchResourceData();
await updateResource(data);
return { success: true, data };
}
);
// The lock is automatically released when the function completes
// (even if an exception is thrown)Basic Lock Operations
// Acquire a lock
const lockResult = await client.acquireLock(
'resource-key',
'my-client-id',
'PT1M' // 1 minute lock
);
// Check the lock status
const lockStatus = await client.getLock('resource-key');
// Use the resource while locked
await doSomethingWithResource();
// Release the lock
await client.releaseLock(
'resource-key',
'my-client-id',
lockResult.payload.unlockCode
);Working with Lock Contention
// Try to acquire a lock with limited attempts
const tryResult = await client.tryAcquireLock(
'resource-key',
'my-client-id',
'PT10S',
{
maxAttempts: 3, // Try 3 times
delayMs: 500 // Wait 500ms between attempts
}
);
if (tryResult.success) {
// Lock was acquired
// Use resource then release the lock
await client.releaseLock(
'resource-key',
'my-client-id',
tryResult.result.payload.unlockCode
);
} else {
// Could not acquire lock after max attempts
}Safe Lock Release
// Try to release a lock with error handling
const releaseResult = await client.tryReleaseLock(
'resource-key',
'my-client-id',
unlockCode
);
if (releaseResult.success) {
console.log(`Lock released successfully in ${releaseResult.time}ms`);
} else {
console.error(`Failed to release lock: ${releaseResult.error.message}`);
// Handle specific error types
if (releaseResult.error.isContention) {
// Handle contention errors
} else if (releaseResult.error.isAuthError) {
// Handle authentication errors
}
}
#### Batch Operations
```javascript
// Create multiple lock requests
const requests = [
{ key: 'resource-1', requisitioner: 'my-client', duration: 'PT15S' },
{ key: 'resource-2', requisitioner: 'my-client', duration: 'PT15S' },
{ key: 'resource-3', requisitioner: 'my-client', duration: 'PT15S' }
];
// Acquire locks in batch
const batchResults = await client.acquireBatch(requests);
console.log(`Acquired ${batchResults.filter(r => r.status === 'Success').length} of ${requests.length} locks`);
// Prepare locks for release
const unlockRequests = batchResults
.filter(result => result.status === 'Success')
.map(result => ({
key: result.payload.key,
requisitioner: 'my-client',
unlockCode: result.payload.unlockCode
}));
// Release locks in batch
const releaseResults = await client.releaseBatch(unlockRequests);
// Note: For performance testing and metrics gathering only, you could use acquireBatchV2
// This is NOT recommended for production useCleaning Up Resources
// Close the client when done to clean up resources
client.close();Mail Gateway Client
The DIOS Mail Gateway Client provides a way to send emails through the DIOS Mail Gateway service.
Creating a Client
import { DiosMailGatewayClient } from '@ditype/dios-client-js';
// Create client instance
const mailClient = new DiosMailGatewayClient(
'https://your-mail-gateway-url',
'your-jwt-token',
{
retryCount: 3, // How many times to retry failed requests
retryDelay: 1000, // Base delay between retries in ms
timeout: 10000, // Request timeout in ms
setTrustAll: true, // For self-signed certificates
setVerifyHost: false // Disable hostname verification
}
);Sending a Simple Email
// Send a single email
const result = await mailClient.send({
emailID: '[email protected]',
firstName: 'John',
lastName: 'Doe',
subject: 'Test Email',
body: 'Hello {{.Name}},\n\nThis is a test email.',
params: {
'Name': 'John Doe' // Parameters for template substitution
},
replyToID: '[email protected]',
fromID: '[email protected]'
});
if (result.success) {
console.log('Email sent successfully!');
} else {
console.error(`Failed to send email: ${result.explanation}`);
}Sending Emails to Multiple Recipients
// Send emails to multiple recipients
const batchResult = await mailClient.sendAll([
{
emailID: '[email protected]',
firstName: 'John',
lastName: 'Doe',
subject: 'Batch Email Test 1',
body: 'Hello {{.Name}},\n\nThis is test email 1.',
params: { 'Name': 'John Doe' },
replyToID: '[email protected]',
fromID: '[email protected]'
},
{
emailID: '[email protected]',
firstName: 'Jane',
lastName: 'Smith',
subject: 'Batch Email Test 2',
body: 'Hello {{.Name}},\n\nThis is test email 2.',
params: { 'Name': 'Jane Smith' },
replyToID: '[email protected]',
fromID: '[email protected]'
}
]);
console.log(`Emails sent: ${batchResult.totalSent}`);
console.log(`Emails failed: ${batchResult.totalFailed}`);
if (batchResult.failedRecipients.length > 0) {
console.error('Failed recipients:', batchResult.failedRecipients);
}Working with Advanced Templates
// Create a more complex email template with multiple variables
const emailTemplate = `
Dear {{.Name}},
Thank you for your interest in {{.CompanyName}}. We're excited to share
information about our {{.ProductName}} offering.
**Account Details:**
- Account ID: {{.AccountID}}
- Subscription Level: {{.SubscriptionLevel}}
- Registration Date: {{.RegistrationDate}}
**Recent Activity:**
{{.RecentActivity}}
**Next Steps:**
1. Review your {{.DocumentType}} at {{.DocumentLink}}
2. Schedule your {{.MeetingType}} by contacting {{.ContactPerson}}
3. Explore our {{.FeatureName}} using the dashboard
If you have any questions about your {{.ServiceType}} service,
please don't hesitate to reach out to our support team at {{.SupportEmail}}.
Thank you for choosing {{.CompanyName}}. We look forward to a productive partnership.
Best regards,
{{.SenderName}}
{{.SenderTitle}}
{{.CompanyName}}
{{.ContactEmail}}
{{.PhoneNumber}}
`;
// Create a comprehensive set of parameters
const emailParams = {
'Name': 'John Doe',
'CompanyName': 'DIOS Technologies',
'ProductName': 'Mail Gateway Service',
'AccountID': 'ACC-12345-XYZ',
'SubscriptionLevel': 'Premium',
'RegistrationDate': 'March 1, 2025',
'RecentActivity': 'You sent 250 emails in the last 30 days',
'DocumentType': 'service agreement',
'DocumentLink': 'https://docs.example.com/agreement',
'MeetingType': 'onboarding session',
'ContactPerson': 'Jane Smith',
'FeatureName': 'analytics dashboard',
'ServiceType': 'email delivery',
'SupportEmail': '[email protected]',
'SenderName': 'Alex Johnson',
'SenderTitle': 'Customer Success Manager',
'ContactEmail': '[email protected]',
'PhoneNumber': '+1 (555) 123-4567'
};
// Send the email with the complex template
const result = await mailClient.send({
emailID: '[email protected]',
firstName: 'John',
lastName: 'Doe',
subject: 'Advanced Template Example',
body: emailTemplate,
params: emailParams,
replyToID: '[email protected]',
fromID: '[email protected]'
});Custom Validation Options
// Specify custom validation options
const result = await mailClient.send(
{
emailID: '[email protected]',
firstName: 'John',
lastName: 'Doe',
subject: 'Email with Custom Validation',
body: 'Hello {{.Name}},\n\nThis is a test email.',
params: { 'Name': 'John Doe' },
replyToID: '[email protected]',
fromID: '[email protected]'
},
{
requireFirstName: true,
requireLastName: true,
requireReplyToID: true,
validateTemplateVars: true,
maxLengths: {
subject: 100, // Limit subject to 100 chars
body: 5000 // Limit body to 5000 chars
}
}
);Cleaning Up Resources
// Close the client when done to clean up resources
mailClient.close();Advanced Use Case: Combining Lock Service with S3 Operations
This example shows how to protect S3 operations with the Lock Service:
import { DiosLockServiceClient } from '@ditype/dios-client-js';
import { makeGatewayRequest, ES3GatewayRequestTypes } from '@ditype/amazon-s3-gateway';
// Create lock client with all relevant options
const lockClient = new DiosLockServiceClient(
'https://lock-service-url',
'lock-jwt-token',
{
retryCount: 3, // Affects normal API requests
retryDelay: 200, // Base delay between retries in ms
contentionRetryCount: 5, // Important for withLock - how many times to retry on contention
contentionRetryDelay: 100, // Important for withLock - delay between contention retries
timeout: 5000, // Request timeout in ms
setTrustAll: true, // For self-signed certificates
setVerifyHost: false // Disable hostname verification
}
);
// Function to put data to S3 with lock protection
async function putDataWithLock(key, data) {
return lockClient.withLock(
key, // Use the same key for lock and S3
'my-client-id',
'PT10S', // Lock for 10 seconds
async () => {
// S3 PUT operation while resource is locked
const result = await makeGatewayRequest({
token: 's3-jwt-token',
method: ES3GatewayRequestTypes.POST,
url: `https://s3-gateway-url/${key}`,
data: { data: { value: data } },
// Other required S3 gateway parameters...
});
return result;
}
);
}
// Function to get data from S3 with lock protection
async function getDataWithLock(key) {
return lockClient.withLock(
key,
'my-client-id',
'PT10S',
async () => {
// S3 GET operation while resource is locked
const result = await makeGatewayRequest({
token: 's3-jwt-token',
method: ES3GatewayRequestTypes.GET,
url: `https://s3-gateway-url/${key}`,
// Other required S3 gateway parameters...
});
return result;
}
);
}License
Currently restricted to internal developers and users. Copyright CI Contextual Intelligence AG, Switzerland.
