Runtime multi-language support - schema-dsl
📋 Overview
schema-dsl's s.error and I18nError support runtime specification of language without modifying global language settings.
This is particularly useful for API development, where error messages in the corresponding language can be dynamically returned based on the language preference of each request (such as the Accept-Language request header).
🆕 Intelligent parameter recognition (v1.1.8)
New in v1.1.8: Support simplified syntax, reduced from 4 parameters to 2 parameters
Intelligent recognition rules:
- The second parameter is
string→ recognized as a language parameter - The second parameter is
object→ recognized as a parameter object - The second parameter is
null/undefined/array→ use the default value
🎨 Supported template syntax (v1.1.4+)
schema-dsl now supports multiple template syntax formats, providing better compatibility:
Example:
Backward Compatibility:
- ✅ Existing
{{#variable}}formats are fully compatible - ✅ All unit tests passed
- ✅ No breaking changes
🎯Three ways to use
Method 1: Simplified syntax (v1.1.8 recommended)⭐
Applicable scenarios:
- No parameter interpolation required
- Most common in API development
- The most concise code
Method 2: Global language settings (traditional method)
Applicable scenarios:
- Single language application
- No need to switch languages dynamically
- Simple error handling
Method 3: Specify language at runtime (recommended for API)⭐
Applicable scenarios:
- Multilingual API
- Dynamically return multi-language errors based on request headers
- Multiple languages required in the same request
- Error propagation in microservice architecture
🔧 API parameters
s.error.create()
s.error.throw()
s.error.assert()
💡 Practical application scenarios
Scenario 1: Multi-language errors are returned based on request headers in Express/Koa
Scenario 2: Error propagation in microservice architecture
Scenario 3: Multiple languages used in the same request
Scenario 4: Multilingual errors in GraphQL Resolver
🔍 Runtime language vs global language
Comparison table
Concurrency safety
Global Language (not recommended for multi-language APIs):
Runtime Language (recommended):
📊 Test validation
Runtime language testing
Runtime language with parameters
🎯 Best Practices
1. Always use runtime language in API development
2. Unified encapsulation language acquisition logic
3. Pass locale between microservices
📝 Backwards compatible
✅ Fully backwards compatible
- Existing code does not need to be modified
localeParameters are optional parameters- Use the global language when
localeis not passed - Relevant unit tests have been covered
🔗 Related documents
Corresponding sample file
Example entry: runtime-locale-support.ts Description: Overrides the key behavior of specifying locale creation error objects at runtime, parameter interpolation, and "local language switching does not pollute the global state".