deepl-node

repository·main·Indexed 19 days ago

https://github.com/deepl/deepl-node

The official Node.js client library for the DeepL API. It enables developers to integrate high-quality language translation for text and documents, manage multilingual glossaries, apply style rules, use translation memories, and rephrase text with specific writing styles and tones into their Node.js applications.

Tokens
10.6K
Snippets
31
Records
46
Agent score
65%

What's inside deepl-node

  1. Understand the difference between GlossaryInfo and MultilingualGlossaryInfo

    main

    The transition to v3 introduces a new mental model for how glossaries are structured:

    • v2 (Monolingual): Uses GlossaryInfo. A glossary is tied to a single language pair (sourceLang and targetLang).
    • v3 (Multilingual): Uses MultilingualGlossaryInfo. A single glossary can contain multiple "glossary dictionaries". Each dictionary within the glossary specifies its own sourceLangCode, targetLangCode, and its own set of entries.

    To manage entries in v3, use the MultilingualGlossaryDictionaryEntries object, which encapsulates a specific dictionary's language pair and its entries.

  2. Migrate from monolingual to multilingual glossaries

    main

    The DeepL API has introduced v3 endpoints that support multilingual glossaries. While v2 methods for monolingual glossaries (e.g., createGlossary(), getGlossary()) remain available, you should transition to the new v3 methods to access enhanced functionality like multiple language pairs within a single glossary and editing capabilities.

    Key Method Mapping

    Monolingual (v2)Multilingual (v3)Change Summary
    createGlossary()createMultilingualGlossary()Accepts an array of MultilingualGlossaryDictionaryEntries; returns MultilingualGlossaryInfo
    createGlossaryWithCsv()createMultilingualGlossaryWithCsv()Returns MultilingualGlossaryInfo
    getGlossary()getMultilingualGlossary()Returns MultilingualGlossaryInfo; accepts MultilingualGlossaryInfo as a parameter
    listGlossaries()listMultilingualGlossaries()Returns a list of MultilingualGlossaryInfo objects
    getGlossaryEntries()getMultilingualGlossaryDictionaryEntries()Requires specifying sourceLang and targetLang; returns MultilingualGlossaryDictionaryEntries
    deleteGlossary()deleteMultilingualGlossary()Accepts MultilingualGlossaryInfo as a parameter
  3. Initialize the DeepLClient

    main

    To use the library, import deepl-node and instantiate a DeepLClient using your API authentication key. For production environments, avoid hard-coding the key; instead, retrieve it from environment variables or configuration files.

    All DeepLClient methods return Promises.

    import * as deepl from 'deepl-node';
    
    const authKey = "YOUR_AUTH_KEY";
    const deeplClient = new deepl.DeepLClient(authKey);
  4. Manage DeepL authentication and server configuration via environment variables

    main

    You can configure the library using environment variables. This is useful for switching between local development (using a mock server) and production environments.

    Key Environment Variables

    • DEEPL_AUTH_KEY: Your DeepL API authentication key.
    • DEEPL_SERVER_URL: The base URL for the DeepL API (e.g., https://api.deepl.com for production).
    • DEEPL_MOCK_SERVER_PORT: The port used if you are testing against a local mock server.

    Configuration Methods

    1. Using a global .rc file (e.g., ~/.bashrc)

    For local development:

    export DEEPL_MOCK_SERVER_PORT=3000
    export DEEPL_AUTH_KEY=ANY_VALUE
    export DEEPL_SERVER_URL=http://localhost:3000

    For production:

    # Ensure DEEPL_MOCK_SERVER_PORT is unset if previously assigned
    export DEEPL_AUTH_KEY={YOUR_API_KEY}
    export DEEPL_SERVER_URL=https://api.deepl.com

    2. Using a .env file

    This is recommended for isolating variables between projects and avoiding terminal refreshes.

    1. Copy .env.example to a new file named .env.
    2. Edit the .env file with your credentials.
    3. Note: Ensure .env is added to your .gitignore so credentials are not committed to version control.
    # Example .env content
    DEEPL_AUTH_KEY=your_api_key_here
    DEEPL_SERVER_URL=https://api.deepl.com
  5. Run tests for deepl-node

    main

    Execute the test suite using npm test.

    Important Considerations:

    • API Usage: By default, tests communicate with the real DeepL API using the key provided in DEEPL_AUTH_KEY. These requests contribute toward your API usage limits.
    • Mock Server Testing: You can run tests against a mock server (using deepl-mock) to test client error-handling without consuming API quota. To do this, run the mock server in a separate terminal and execute the tests with the following variables defined:
      • DEEPL_MOCK_SERVER_PORT
      • DEEPL_SERVER_URL
    npm test
  6. Get a DeepL API authentication key

    main
    To use the library, you must have a DeepL API authentication key. You can create an account to obtain a key. A DeepL API Free account allows for up to 500,000 characters of translation per month for free.
  7. Configure DeepLClient options

    main

    The DeepLClient constructor accepts an options object as the second argument to configure connection and retry behavior.

    Available Options:

    • maxRetries: number (default 5). Maximum failed HTTP requests to retry per call.
    • minTimeout: number (default 10000). Milliseconds used as connection timeout for each retry. Uses exponential backoff.
    • serverUrl: string. Override the default DeepL API URL.
    • headers: object. Extra HTTP headers. Note: Authorization and User-Agent are added automatically but can be overridden.
    • proxy: object. Define proxy settings (e.g., { host: 'localhost', port: 3000 }). Supports username and password for auth.
    • appInfo: { appName: string, appVersion: string }. Identifies your application to DeepL.
    • sendPlatformInfo: boolean (default true). Set to false to opt-out of sending anonymous platform data in the User-Agent.
    const options = {
        maxRetries: 5,
        minTimeout: 10000,
        proxy: { host: 'localhost', port: 3000 },
        appInfo: { appName: 'myApp', appVersion: '1.0.0' }
    };
    const deepl = new deepl.DeepLClient('YOUR_AUTH_KEY', options);
  8. Monitor document translation status

    main

    Document translations are often asynchronous. You can track progress using a DocumentStatus object, which provides:

    • status: The current state ('queued', 'translating', 'error', or 'done').
    • ok(): Returns true if no error has occurred (returns true even while in progress).
    • done(): Returns true if the translation is successfully completed.
    • secondsRemaining: Estimated time until completion in seconds.
    • billedCharacters: Number of characters billed (available once translation is complete or known).
    • errorMessage: A short description if an error occurred.
  9. Manage style rules

    main

    Style rules allow you to manage shared settings for style, formatting, and tone.

    Key Operations:

    • createStyleRule(name, language): Creates a new rule.
    • getAllStyleRules(page, pageSize, detailed): Lists all rules. If detailed is true, includes configuredRules and customInstructions.
    • getStyleRule(id): Retrieves a single rule.
    • updateStyleRuleName(id, newName): Renames a rule.
    • updateStyleRuleConfiguredRules(id, configuredRules): Updates rule settings (e.g., { style_and_tone: { formality: 'formal' } }).
    • deleteStyleRule(id): Deletes a rule.

    Custom Instructions: You can manage free-text prompts within a style rule using:

    • createStyleRuleCustomInstruction(styleId, label, instruction)
    • getStyleRuleCustomInstruction(styleId, instructionId)
    • updateStyleRuleCustomInstruction(styleId, instructionId, newLabel, newInstruction)
    • deleteStyleRuleCustomInstruction(styleId, instructionId)
  10. Manage multilingual glossaries

    main

    Glossaries allow you to enforce specific translations for defined terms. The library supports the newer /v3 multilingual glossary API.

    Key Operations:

    • createMultilingualGlossary(name, dictionaries): Creates a glossary. dictionaries is an array of objects containing sourceLangCode, targetLangCode, and entries (a GlossaryEntries object).
    • createGlossaryWithCsv(name, sourceLang, targetLang, csvContent): Creates a glossary from a CSV string.
    • listMultilingualGlossaries(): Returns a list of MultilingualGlossaryInfo objects.
    • getMultilingualGlossary(id): Retrieves a specific glossary.
    • getMultilingualGlossaryDictionaryEntries(glossary, sourceLang, targetLang): Returns entries for a specific language pair in the glossary.
    • updateMultilingualGlossaryDictionary(glossary, newDict): Updates or inserts entries for a language pair.
    • replaceMultilingualGlossaryDictionary(glossary, newDict): Replaces all entries for a language pair.
    • deleteMultilingualGlossary(glossary): Deletes the entire glossary.
    • deleteMultilingualGlossaryDictionary(glossary, sourceLang, targetLang): Deletes a specific language pair dictionary within a glossary.

    To use a glossary, pass the glossary ID or MultilingualGlossaryInfo object into the glossary option of translateText() or translateDocument().

    // Create a glossary
    const entries = new deepl.GlossaryEntries({ entries: { artist: 'Maler', prize: 'Gewinn' } });
    const glossaryEnToDe = await deeplClient.createMultilingualGlossary('My glossary', [
        { sourceLangCode: 'en', targetLangCode: 'de', entries }
    ]);
    
    // Use the glossary
    const result = await deeplClient.translateText(
        'The artist was awarded a prize.',
        'en',
        'de',
        { glossary: glossaryEnToDe }
    );
  11. List and delete multilingual glossaries

    main

    Use listMultilingualGlossaries() to retrieve all glossaries associated with your account. To remove a glossary, use deleteMultilingualGlossary(), which accepts a MultilingualGlossaryInfo object.

    // multilingual glossary example
    const glossaries = await deeplClient.listMultilingualGlossaries();
    for (const glossary of glossaries) {
      if (glossary.name === "Old glossary") {
        await deeplClient.deleteMultilingualGlossary(glossary);
      }
    }