Skip to content

lazy-js/l10n-js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Lazy Localization Client SDK

A TypeScript/JavaScript client SDK for interacting with the Lazy Localization Service. This SDK provides methods to check language support and retrieve default language settings from a remote localization service with comprehensive error handling and type safety.

TypeScript License: ISC

πŸš€ Features

  • TypeScript Support - Full TypeScript definitions and type safety
  • Dual Module Support - Both ESM and CommonJS compatibility
  • Comprehensive Error Handling - Custom error types with detailed context
  • Service Availability Checking - Built-in service health monitoring
  • Flexible Configuration - Customizable service URLs and API prefixes
  • Zero Dependencies - Lightweight with minimal external dependencies

πŸ“¦ Installation

# Using npm
npm install github:lazy-js/l10n-js

# Using yarn
yarn add github:lazy-js/l10n-js

# Using pnpm
pnpm add github:lazy-js/l10n-js

πŸƒβ€β™‚οΈ Quick Start

Basic Usage

import { LazyLocalizationClientSdk } from '@lazy-js/l10n-js';

// Create SDK instance with default configuration
const sdk = new LazyLocalizationClientSdk();

// Check if service is available
const isAvailable = await sdk.avialable();
if (isAvailable) {
    // Get default language
    const defaultLang = await sdk.getDefaultLanguage();
    console.log('Default language:', defaultLang); // Output: 'en'

    // Check if a language is supported
    const isSupported = await sdk.isLanguageSupported('en-US');
    console.log('English supported:', isSupported); // Output: true
}

Custom Configuration

import { LazyLocalizationClientSdk } from '@lazy-js/l10n-js';

// Create SDK with custom configuration
const sdk = new LazyLocalizationClientSdk({
    serviceName: 'MyApp-Localization',
    localizationServiceUrl: 'https://api.mycompany.com',
    localizationServiceRouterPrefix: '/api/v2',
});

πŸ“– API Reference

LazyLocalizationClientSdk

The main SDK class that provides methods for interacting with the localization service.

Constructor

new LazyLocalizationClientSdk(params?: LocalizationClientSdkParams)

Parameters:

  • params (optional): Configuration object
    • serviceName?: string - Custom service name for error reporting
    • localizationServiceUrl?: string - Base URL for the localization service
    • localizationServiceRouterPrefix?: string - API prefix for the service endpoints

Methods

getDefaultLanguage(): Promise<string>

Retrieves the default language code from the localization service.

Returns: Promise that resolves to the default language code (e.g., 'en', 'es', 'fr')

Throws:

  • InternalError - When the service is not available or response is incompatible
  • ExternalServiceError - When the service returns an error response
  • NetworkError - When there's a network connectivity issue

Example:

try {
    const defaultLang = await sdk.getDefaultLanguage();
    console.log('Default language:', defaultLang);
} catch (error) {
    console.error('Failed to get default language:', error.message);
}
isLanguageSupported(languageCode: string): Promise<boolean>

Checks if a specific language code is supported by the localization service.

Parameters:

  • languageCode: string - The language code to check (e.g., 'en-US', 'es-ES', 'fr-FR')

Returns: Promise that resolves to true if the language is supported, false otherwise

Throws:

  • InternalError - When the service is not available or response is incompatible
  • ExternalServiceError - When the service returns an error response
  • NetworkError - When there's a network connectivity issue

Example:

try {
    const isEnglishSupported = await sdk.isLanguageSupported('en-US');
    console.log('English supported:', isEnglishSupported);

    const isKlingonSupported = await sdk.isLanguageSupported('tlh');
    console.log('Klingon supported:', isKlingonSupported);
} catch (error) {
    console.error('Failed to check language support:', error.message);
}

πŸ”§ Configuration

Environment Variables

You can configure the SDK using environment variables:

const sdk = new LazyLocalizationClientSdk({
    serviceName: process.env.LOCALIZATION_SERVICE_NAME || 'LOCALIZATION-SDK',
    localizationServiceUrl: process.env.LOCALIZATION_SERVICE_URL || 'http://localhost:8085',
    localizationServiceRouterPrefix: process.env.LOCALIZATION_API_PREFIX || '/api/v1',
});

Default Configuration

Parameter Default Value
serviceName 'LOCALIZATION-SDK'
localizationServiceUrl 'http://localhost:8085'
localizationServiceRouterPrefix '/api/v1'

🎯 Usage Examples

React Integration

import React, { useState, useEffect } from 'react';
import { LazyLocalizationClientSdk } from '@lazy-js/l10n-js';

const LanguageSelector: React.FC = () => {
    const [defaultLang, setDefaultLang] = useState<string>('');
    const [supportedLanguages, setSupportedLanguages] = useState<string[]>([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const sdk = new LazyLocalizationClientSdk();

        const initializeLanguages = async () => {
            try {
                // Check if service is available
                if (!(await sdk.avialable())) {
                    throw new Error('Localization service is not available');
                }

                // Get default language
                const defaultLanguage = await sdk.getDefaultLanguage();
                setDefaultLang(defaultLanguage);

                // Check support for common languages
                const languages = ['en-US', 'es-ES', 'fr-FR', 'de-DE', 'it-IT'];
                const supported = await Promise.all(
                    languages.map(async (lang) => ({
                        code: lang,
                        supported: await sdk.isLanguageSupported(lang),
                    }))
                );

                setSupportedLanguages(supported.filter((lang) => lang.supported).map((lang) => lang.code));
            } catch (error) {
                console.error('Error initializing languages:', error);
            } finally {
                setLoading(false);
            }
        };

        initializeLanguages();
    }, []);

    if (loading) return <div>Loading languages...</div>;

    return (
        <div>
            <p>Default Language: {defaultLang}</p>
            <select>
                {supportedLanguages.map((lang) => (
                    <option key={lang} value={lang}>
                        {lang}
                    </option>
                ))}
            </select>
        </div>
    );
};

Error Handling

import { LazyLocalizationClientSdk, InternalError, ExternalServiceError, NetworkError } from '@lazy-js/l10n-js';

const sdk = new LazyLocalizationClientSdk();

const handleLanguageCheck = async (languageCode: string) => {
    try {
        const isSupported = await sdk.isLanguageSupported(languageCode);
        return isSupported;
    } catch (error) {
        if (error instanceof InternalError) {
            console.error('Service configuration error:', error.message);
            // Handle internal errors (service unavailable, incompatible response)
        } else if (error instanceof ExternalServiceError) {
            console.error('Service returned error:', error.message);
            // Handle service-specific errors
        } else if (error instanceof NetworkError) {
            console.error('Network error:', error.message);
            // Handle network connectivity issues
        } else {
            console.error('Unknown error:', error);
        }
        return false;
    }
};

Batch Language Checking

const checkMultipleLanguages = async (languageCodes: string[]) => {
    const sdk = new LazyLocalizationClientSdk();

    try {
        const results = await Promise.all(
            languageCodes.map(async (code) => ({
                code,
                supported: await sdk.isLanguageSupported(code),
            }))
        );

        return results.filter((result) => result.supported);
    } catch (error) {
        console.error('Error checking languages:', error);
        return [];
    }
};

// Usage
const languages = ['en-US', 'es-ES', 'fr-FR', 'de-DE'];
const supportedLanguages = await checkMultipleLanguages(languages);
console.log('Supported languages:', supportedLanguages);

πŸ—οΈ Development

Prerequisites

  • Node.js 16+
  • npm, yarn, or pnpm

Building

# Install dependencies
npm install

# Build both ESM and CommonJS modules
npm run build

# Build ESM only
npm run build:esm

# Build CommonJS only
npm run build:cjs

# Watch mode for development
npm run dev

Testing

# Run tests
npm test

# Run tests in watch mode
npm run test:watch

Project Structure

src/
β”œβ”€β”€ core/
β”‚   └── index.ts          # Main SDK implementation
β”œβ”€β”€ __tests__/
β”‚   └── index.test.ts     # Test files
β”œβ”€β”€ constants.ts          # Configuration constants
β”œβ”€β”€ errors.ts            # Error definitions
└── types.ts             # TypeScript type definitions

πŸ“‹ TypeScript Support

This package includes full TypeScript definitions. Import types as needed:

import type {
    ILazyLocalizationClientSdk,
    LocalizationClientSdkParams,
    IsLanguageSupportedSuccessResponse,
    GetDefaultLanguageSuccessResponse,
} from '@lazy-js/l10n-js';

πŸ” Error Codes

The SDK uses specific error codes for different scenarios:

Error Code Description
LOCALIZATION_SDK_NOT_AVAILABLE Service is not reachable or unavailable
LOCALIZATION_SDK_NOT_COMPATIBLE Service response format is incompatible
LOCALIZATION_SDK_UNKNOWN_ERROR Unexpected error occurred

πŸ“„ License

This project is licensed under the ISC License - see the LICENSE file for details.

πŸ†˜ Support

  • Documentation: Check the JSDoc comments in the source code
  • Issues: Report bugs and request features on GitHub
  • Discussions: Join community discussions for questions and ideas

πŸ”— Related Packages

  • @lazy-js/client-sdk - Base client SDK functionality
  • @lazy-js/error-guard - Error handling utilities

Made with ❀️ by the Lazy JS Team

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published