Integrating i18n for Localized API Responses in the GitHub Streak Stats API

Project Context: GitHub Streak Stats API

The FlavioKde/github-streak-stats-api project provides a service to generate SVG images displaying GitHub streak statistics. These stats, such as current streak, longest streak, and total contributions, are valuable for developers showcasing their activity. To enhance user experience, a recent update focused on introducing internationalization (i18n) capabilities to the API's JSON responses.

The Challenge of Global Reach

While the SVG output is visual, the underlying JSON data that drives it, or that might be consumed by other applications, needs to be easily understandable by users around the world. Previously, the API would return streak-related messages in a single language. The goal was to allow users to specify their preferred language and receive localized text within the JSON output, maintaining clear separation of concerns within the codebase.

Integrating Localization: A Step-by-Step Approach

The implementation involved introducing a new translation mechanism directly into the API's core handler, ensuring that computed streak data could be presented in the user's chosen language.

Step 1: Capturing Language Preference

The first step was to identify the user's language preference. This was achieved by inspecting the lang query parameter in the incoming API request. If provided, this parameter would dictate the language for the response.

Step 2: Initializing the Translator

Once the language was identified, a dedicated createTranslator function was used to initialize a translator instance. This instance would encapsulate the logic for mapping specific keys to localized strings based on the selected language. This keeps translation logic separate from the main data processing.

Step 3: Localizing the JSON Response

With the translator ready, the API's handler was updated. After computing the core streak data using a calculateStreak domain function, the formatJsonResponse utility was applied. This function takes the raw streak data and the initialized translator, processes the data, and embeds localized strings where necessary, preparing the final JSON output.

Code Example: The API Handler in Action

This simplified JavaScript snippet illustrates how the language preference is picked up, the translator is initialized, and the final response is formatted:

// In a hypothetical API handler function
async function handleStreakRequest(req, res) {
  const lang = req.query.lang || 'en'; // Default to English if no language specified

  // Assume createTranslator loads locale files based on 'lang'
  const t = createTranslator(lang);

  // calculateStreak is a domain function that computes raw streak metrics
  const rawStreakData = await calculateStreak(req.params.username);

  // formatJsonResponse applies localization using the translator 't'
  const localizedResponse = formatJsonResponse(rawStreakData, t);

  res.status(200).json(localizedResponse);
}

// A simplified conceptual example of formatJsonResponse
function formatJsonResponse(data, translator) {
  return {
    totalContributions: data.totalContributions,
    currentStreak: {
      count: data.currentStreak.count,
      label: translator.get('streak.current_label', { count: data.currentStreak.count }),
    },
    longestStreak: {
      count: data.longestStreak.count,
      label: translator.get('streak.longest_label', { count: data.longestStreak.count }),
    },
    // ... other localized fields
  };
}

This approach ensures that the main logic for calculating streaks remains clean and focused, while the presentation layer handles the intricacies of internationalization.

The Outcome

By integrating this i18n mechanism, the GitHub Streak Stats API can now deliver localized JSON responses, making it more accessible and user-friendly for a global audience. This not only improves the immediate utility for consumers of the JSON output but also lays a robust foundation for future language expansions without overhauling core logic.

Next Steps

For further enhancement, consider expanding the set of supported languages based on user demand and refining the translation file management system. Implementing a caching mechanism for translated strings could also improve performance for frequently requested locales.


Generated with Gitvlg.com

Integrating i18n for Localized API Responses in the GitHub Streak Stats API
Flavio A. D'Avirro

Flavio A. D'Avirro

Author

Share: